Debian Codegraph @

src/shared/tar-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "errno-util.h"
4 #include "log.h"
5 #include "tar-util.h"
6
7 #if HAVE_LIBARCHIVE
8 #include <sys/mount.h>
9 #include <sys/sysmacros.h>
10
11 #include "acl-util.h"
12 #include "alloc-util.h"
13 #include "chase.h"
14 #include "chattr-util.h"
15 #include "fd-util.h"
16 #include "fs-util.h"
17 #include "hexdecoct.h"
18 #include "iovec-util.h"
19 #include "libarchive-util.h"
20 #include "mountpoint-util.h"
21 #include "nsresource.h"
22 #include "nulstr-util.h"
23 #include "path-util.h"
24 #include "recurse-dir.h"
25 #include "rm-rf.h"
26 #include "sha256.h"
27 #include "stat-util.h"
28 #include "string-util.h"
29 #include "tmpfile-util.h"
30 #include "user-util.h"
31 #include "xattr-util.h"
32
33 #define DEPTH_MAX 128U
34
35 /* We are a bit conservative with the flags we save/restore in tar files */
36 #define CHATTR_TAR_FL \
37 (FS_NOATIME_FL | \
38 FS_NOCOW_FL | \
39 FS_PROJINHERIT_FL | \
40 FS_NODUMP_FL | \
41 FS_SYNC_FL | \
42 FS_DIRSYNC_FL)
43
44 typedef struct XAttr {
45 char *name;
46 struct iovec data;
47 } XAttr;
48
49 typedef struct OpenInode {
50 int fd;
51 char *path;
52
53 /* File properties to apply when we are done with the inode, i.e. right before closing it */
54 mode_t filetype;
55 mode_t mode;
56 struct timespec mtime;
57 uid_t uid;
58 gid_t gid;
59 unsigned fflags;
60 XAttr *xattr;
61 size_t n_xattr;
62 acl_t acl_access, acl_default;
63 } OpenInode;
64
65 static void xattr_done(XAttr *xa) {
66 assert(xa);
67
68 free(xa->name);
69 iovec_done(&xa->data);
70 }
71
72 static DEFINE_ARRAY_FREE_FUNC(xattr_free_array, XAttr, xattr_done);
73
74 static void open_inode_done(OpenInode *of) {
75 assert(of);
76
77 if (of->path) {
78 /* Only close the stored fd if the path field is set. We'll set the path to NULL for the root
79 * inode, and we don't want the fd for that closed, as it's owned by the caller. */
80 of->fd = safe_close(of->fd);
81 of->path = mfree(of->path);
82 }
83 xattr_free_array(of->xattr, of->n_xattr);
84 #if HAVE_ACL
85 if (of->acl_access)
86 sym_acl_free(of->acl_access);
87 if (of->acl_default)
88 sym_acl_free(of->acl_default);
89 #endif
90 }
91
92 static DEFINE_ARRAY_FREE_FUNC(open_inode_free_array, OpenInode, open_inode_done);
93
94 static int open_inode_apply_acl(OpenInode *of) {
95 int r = 0;
96
97 assert(of);
98 assert(of->fd >= 0);
99
100 if (!inode_type_can_acl(of->filetype))
101 return 0;
102
103 if (of->acl_access) {
104 #if HAVE_ACL
105 if (sym_acl_set_fd(of->fd, of->acl_access) < 0)
106 RET_GATHER(r, log_error_errno(errno, "Failed to adjust ACLs of '%s': %m", of->path));
107 #else
108 log_debug("The archive entry '%s' has ACLs, but ACL support is disabled.", of->path);
109 #endif
110 }
111
112 if (of->filetype == S_IFDIR && of->acl_default) {
113 #if HAVE_ACL
114 /* There's no API to set default ACLs by fd, hence go by /proc/self/fd/ path */
115 if (sym_acl_set_file(FORMAT_PROC_FD_PATH(of->fd), ACL_TYPE_DEFAULT, of->acl_default) < 0)
116 RET_GATHER(r, log_error_errno(errno, "Failed to adjust default ACLs of '%s': %m", of->path));
117 #else
118 log_debug("The archive entry '%s' has default ACLs, but ACL support is disabled.", of->path);
119 #endif
120 }
121
122 return r;
123 }
124
125 static int open_inode_finalize(OpenInode *of) {
126 int r = 0;
127
128 assert(of);
129
130 if (of->fd >= 0) {
131 int k;
132
133 /* We adjust the UID/GID right before the mode, since doing this might affect the mode (drops
134 * suid/sgid bits).
135 *
136 * We adjust the mode only when leaving a dir, because if we are unprivileged we might lose
137 * the ability to enter it once we do this. */
138
139 if (uid_is_valid(of->uid) || gid_is_valid(of->gid) || of->mode != MODE_INVALID) {
140 k = fchmod_and_chown_with_fallback(of->fd, /* path= */ NULL, of->mode, of->uid, of->gid);
141 if (k < 0)
142 RET_GATHER(r, log_error_errno(k, "Failed to adjust ownership/mode of '%s': %m", of->path));
143 }
144
145 k = open_inode_apply_acl(of);
146 if (k < 0)
147 RET_GATHER(r, log_error_errno(k, "Failed to adjust ACL of '%s': %m", of->path));
148
149 if ((of->fflags & ~CHATTR_EARLY_FL) != 0 && inode_type_can_chattr(of->filetype)) {
150 k = chattr_full(of->fd,
151 /* path= */ NULL,
152 /* value= */ of->fflags,
153 /* mask= */ of->fflags & ~CHATTR_EARLY_FL,
154 /* ret_previous= */ NULL,
155 /* ret_final= */ NULL,
156 CHATTR_FALLBACK_BITWISE);
157 if (ERRNO_IS_NEG_NOT_SUPPORTED(k))
158 log_warning_errno(k, "Failed to apply chattr of '%s', ignoring: %m", of->path);
159 else if (k < 0)
160 RET_GATHER(r, log_error_errno(k, "Failed to adjust chattr of '%s': %m", of->path));
161 }
162
163 /* We also adjust the mtime only after leaving a dir, since it might otherwise change again
164 * because we make modifications inside it */
165 if (of->mtime.tv_nsec != UTIME_OMIT) {
166 k = futimens_opath(of->fd, (const struct timespec[2]) {
167 { .tv_nsec = UTIME_OMIT },
168 of->mtime,
169 });
170 if (k < 0)
171 RET_GATHER(r, log_error_errno(k, "Failed to adjust mtime of '%s': %m", of->path));
172 }
173
174 /* Setting certain xattrs might cause us to lose access to the inode, hence set this last */
175 FOREACH_ARRAY(i, of->xattr, of->n_xattr) {
176 k = xsetxattr_full(
177 of->fd,
178 /* path= */ NULL,
179 AT_EMPTY_PATH,
180 i->name,
181 i->data.iov_base,
182 i->data.iov_len,
183 /* xattr_flags= */ 0);
184 if (k < 0)
185 RET_GATHER(r, log_error_errno(k, "Failed to set xattr '%s' of '%s': %m", i->name, of->path));
186 }
187 }
188
189 open_inode_done(of); /* free this item even on failure */
190 return r;
191 }
192
193 static int open_inode_finalize_many(OpenInode **array, size_t *n) {
194 int r = 0;
195 assert(array);
196 assert(n);
197 assert(*array || *n == 0);
198
199 /* Go backwards, so that we adjust innermost first */
200 for (size_t i = *n; i > 0; i--)
201 RET_GATHER(r, open_inode_finalize(*array + i - 1));
202
203 *array = mfree(*array);
204 *n = 0;
205 return r;
206 }
207
208 static int archive_unpack_regular(
209 struct archive *a,
210 struct archive_entry *entry,
211 int parent_fd,
212 const char *filename,
213 const char *path,
214 unsigned fflags) {
215
216 int r;
217
218 assert(a);
219 assert(entry);
220 assert(parent_fd >= 0);
221 assert(filename);
222 assert(path);
223
224 _cleanup_free_ char *tmp = NULL;
225 _cleanup_close_ int fd = open_tmpfile_linkable_at(parent_fd, filename, O_CLOEXEC|O_WRONLY, &tmp);
226 if (fd < 0)
227 return log_error_errno(fd, "Failed to create regular file '%s': %m", path);
228
229 CLEANUP_TMPFILE_AT(parent_fd, tmp);
230
231 if ((fflags & CHATTR_EARLY_FL) != 0) {
232 r = chattr_full(fd,
233 /* path= */ NULL,
234 /* value= */ fflags,
235 /* mask= */ fflags & CHATTR_EARLY_FL,
236 /* ret_previous= */ NULL,
237 /* ret_final= */ NULL,
238 CHATTR_FALLBACK_BITWISE);
239 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
240 log_warning_errno(r, "Failed to apply chattr of '%s', ignoring: %m", path);
241 else if (r < 0)
242 return log_error_errno(r, "Failed to adjust chattr of '%s': %m", path);
243 }
244
245 r = sym_archive_read_data_into_fd(a, fd);
246 if (r != ARCHIVE_OK)
247 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
248 "Failed to unpack regular file '%s': %s", path, sym_archive_error_string(a));
249
250 /* If this is a sparse file, then libarchive's archive_read_data_into_fd() won't insert the final
251 * hole. We need to manually truncate. */
252 off_t l = lseek(fd, 0, SEEK_CUR);
253 if (l < 0)
254 return log_error_errno(errno, "Failed to determine current file position in '%s': %m", path);
255 if (ftruncate(fd, l) < 0)
256 return log_error_errno(errno, "Failed to truncate regular file '%s' to %" PRIu64 ": %m", path, (uint64_t) l);
257
258 r = link_tmpfile_at(fd, parent_fd, tmp, filename, LINK_TMPFILE_REPLACE);
259 if (r < 0)
260 return log_error_errno(r, "Failed to install regular file '%s': %m", path);
261
262 tmp = mfree(tmp); /* disarm CLEANUP_TMPFILE_AT() */
263 return TAKE_FD(fd);
264 }
265
266 static int overlayfs_fsetfattr(
267 const char *path, /* purely decorative, for log purposes */
268 int fd,
269 const char *name, /* xattr key name */
270 const char *value /* xattr value */) {
271 int r;
272
273 assert(fd >= 0);
274 assert(path);
275 assert(name);
276 assert(value);
277
278 /* overlayfs knows magic {user|trusted}.overlay.* xattrs for whiteouts and opaque directories. The
279 * 'user.overlay.*' ones are only checked if overlayfs is mounted with "userxattr". We only set that
280 * one because we want to operate unprivileged. Ideally, we'd set both here, to maximize the chance
281 * that things work both in privileged and unprivileged scenarios, but unfortunately this has the
282 * effect that the privileged ones are ignored (and visible in the overlayfs mount). */
283 _cleanup_free_ char *n = strjoin("user.overlay.", name);
284 if (!n)
285 return log_oom();
286
287 r = xsetxattr(fd, /* path= */ NULL, AT_EMPTY_PATH, n, value);
288 if (r < 0)
289 return log_error_errno(r, "Failed to set '%s' xattr on file '%s': %m", n, path);
290
291 return 0;
292 }
293
294 static int archive_unpack_whiteout(
295 struct archive *a,
296 struct archive_entry *entry,
297 int parent_fd,
298 const char *parent_path, /* Full path of 'parent_fd', purely decorative for log purposes */
299 const char *filename, /* Just the filename we are supposed to whiteout */
300 const char *path /* Full path of the whiteout file, purely decorative for log purposes */) {
301
302 int r;
303
304 assert(a);
305 assert(entry);
306 assert(parent_fd >= 0);
307 assert(parent_path);
308 assert(filename);
309 assert(path);
310
311 _cleanup_free_ char *tmp = NULL;
312 _cleanup_close_ int fd = open_tmpfile_linkable_at(parent_fd, filename, O_CLOEXEC|O_WRONLY, &tmp);
313 if (fd < 0)
314 return log_error_errno(fd, "Failed to create whiteout file for '%s': %m", path);
315
316 CLEANUP_TMPFILE_AT(parent_fd, tmp);
317
318 r = overlayfs_fsetfattr(path, fd, "whiteout", "y");
319 if (r < 0)
320 return r;
321
322 /* As per https://docs.kernel.org/filesystems/overlayfs.html also mark the parent */
323 r = overlayfs_fsetfattr(parent_path, parent_fd, "opaque", "x");
324 if (r < 0)
325 return r;
326
327 r = link_tmpfile_at(fd, parent_fd, tmp, filename, LINK_TMPFILE_REPLACE);
328 if (r < 0)
329 return log_error_errno(r, "Failed to install regular file '%s': %m", path);
330
331 tmp = mfree(tmp); /* disarm CLEANUP_TMPFILE_AT */
332 return 0; /* we do not return an fd here, because this kills an inode, and doesn't synthesize one */
333 }
334
335 static int archive_unpack_opaque(
336 struct archive *a,
337 struct archive_entry *entry,
338 int parent_fd,
339 const char *parent_path) {
340
341 assert(a);
342 assert(entry);
343 assert(parent_fd >= 0);
344 assert(parent_path);
345
346 /* we do not return an fd here either */
347
348 return overlayfs_fsetfattr(parent_path, parent_fd, "opaque", "y");
349 }
350
351 static int archive_unpack_directory(
352 struct archive *a,
353 struct archive_entry *entry,
354 int parent_fd,
355 const char *filename,
356 const char *path,
357 unsigned fflags) {
358
359 int r;
360
361 assert(a);
362 assert(entry);
363 assert(parent_fd >= 0);
364 assert(filename);
365 assert(path);
366
367 /* For the other inode types we operate in an atomic replace fashion, but not for the directories,
368 * they are more of a "shared" concept, and we try to reuse existing inodes. Note that we create the
369 * dir inode in mode 0700, so that we can fully access it (but others cannot). We'll adjust the modes
370 * right before closing the inode. */
371 _cleanup_close_ int fd = open_mkdir_at(parent_fd, filename, O_CLOEXEC, 0700);
372 if (fd < 0)
373 return log_error_errno(fd, "Failed to create directory '%s': %m", path);
374
375 if ((fflags & CHATTR_EARLY_FL) != 0) {
376 r = chattr_full(fd,
377 /* path= */ NULL,
378 /* value= */ fflags,
379 /* mask= */ fflags & CHATTR_EARLY_FL,
380 /* ret_previous= */ NULL,
381 /* ret_final= */ NULL,
382 CHATTR_FALLBACK_BITWISE);
383 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
384 log_warning_errno(r, "Failed to apply chattr of '%s', ignoring: %m", path);
385 else if (r < 0)
386 return log_error_errno(r, "Failed to adjust chattr of '%s': %m", path);
387 }
388
389 return TAKE_FD(fd);
390 }
391
392 static int archive_unpack_symlink(
393 struct archive *a,
394 struct archive_entry *entry,
395 int parent_fd,
396 const char *filename,
397 const char *path) {
398
399 int r;
400
401 assert(a);
402 assert(entry);
403 assert(parent_fd >= 0);
404 assert(filename);
405 assert(path);
406
407 const char *target = sym_archive_entry_symlink(entry);
408 if (!target)
409 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to get symlink target for '%s': %m", path);
410
411 r = symlinkat_atomic_full(target, parent_fd, filename, /* flags= */ 0);
412 if (r < 0)
413 return log_error_errno(r, "Failed to create symlink '%s' → '%s': %m", path, target);
414
415 _cleanup_close_ int fd = openat(parent_fd, filename, O_CLOEXEC|O_PATH|O_NOFOLLOW);
416 if (fd < 0)
417 return log_error_errno(errno, "Failed to open symlink '%s' we just created: %m", path);
418
419 r = fd_verify_symlink(fd);
420 if (r < 0)
421 return log_error_errno(r, "Symlink '%s' we just created is not a symlink: %m", path);
422
423 return TAKE_FD(fd);
424 }
425
426 static int archive_unpack_special_inode(
427 struct archive *a,
428 struct archive_entry *entry,
429 int parent_fd,
430 const char *filename,
431 const char *path,
432 mode_t filetype) {
433
434 int r;
435
436 assert(a);
437 assert(entry);
438 assert(parent_fd >= 0);
439 assert(filename);
440 assert(path);
441
442 dev_t major = 0, minor = 0;
443 if (IN_SET(filetype, S_IFCHR, S_IFBLK)) {
444 major = sym_archive_entry_rdevmajor(entry);
445 minor = sym_archive_entry_rdevminor(entry);
446 }
447
448 r = mknodat_atomic(parent_fd, filename, filetype | 0000, makedev(major, minor));
449 if (r < 0)
450 return log_error_errno(r, "Failed to create special node '%s': %m", path);
451
452 _cleanup_close_ int fd = openat(parent_fd, filename, O_CLOEXEC|O_PATH|O_NOFOLLOW);
453 if (fd < 0)
454 return log_error_errno(errno, "Failed to open special node '%s' we just created: %m", path);
455
456 struct stat st;
457 if (fstat(fd, &st) < 0)
458 return log_error_errno(errno, "Failed to fstat() '%s': %m", path);
459
460 if (((st.st_mode ^ filetype) & S_IFMT) != 0)
461 return log_error_errno(SYNTHETIC_ERRNO(ENODEV),
462 "Special node '%s' we just created is of a wrong type: %m", path);
463
464 return TAKE_FD(fd);
465 }
466
467 static int archive_entry_pathname_safe(struct archive_entry *entry, const char **ret) {
468 /* libarchive prefixes all paths with "./", let's chop that off. Note that we'll return a path of
469 * NULL for the root inode here! */
470
471 assert(entry);
472 assert(ret);
473
474 const char *p = sym_archive_entry_pathname(entry);
475 if (!p)
476 return -EBADMSG;
477
478 const char *e = startswith(p, "./") ?: p;
479 if (isempty(e))
480 *ret = NULL;
481 else if (path_is_safe(e))
482 *ret = e;
483 else
484 return -EBADMSG;
485
486 return 0;
487 }
488
489 static int archive_entry_read_acl(
490 struct archive_entry *entry,
491 acl_type_t ntype,
492 acl_t *acl,
493 TarFlags flags) {
494
495 int r;
496
497 assert(entry);
498 assert(acl);
499
500 int type;
501 if (ntype == ACL_TYPE_ACCESS)
502 type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
503 else if (ntype == ACL_TYPE_DEFAULT)
504 type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT;
505 else
506 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unexpected ACL type");
507
508 int c = sym_archive_entry_acl_reset(entry, type);
509 if (c == 0)
510 return 0;
511 assert(c > 0);
512
513 #if HAVE_ACL
514 r = dlopen_libacl(LOG_DEBUG);
515 if (r < 0)
516 return 0;
517
518 _cleanup_(acl_freep) acl_t a = NULL;
519 a = sym_acl_init(c);
520 if (!a)
521 return log_oom();
522 #endif
523
524 for (;;) {
525 int rtype, permset, tag, qual;
526 const char *name;
527 r = sym_archive_entry_acl_next(
528 entry,
529 type,
530 &rtype,
531 &permset,
532 &tag,
533 &qual,
534 &name);
535 if (r == ARCHIVE_EOF)
536 break;
537 if (r != ARCHIVE_OK)
538 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
539 "Unexpected error while iterating through ACLs.");
540
541 assert(rtype == type);
542
543 static const struct {
544 int libarchive;
545 acl_tag_t libacl;
546 } tag_map[] = {
547 { ARCHIVE_ENTRY_ACL_USER, ACL_USER },
548 { ARCHIVE_ENTRY_ACL_GROUP, ACL_GROUP },
549 { ARCHIVE_ENTRY_ACL_USER_OBJ, ACL_USER_OBJ },
550 { ARCHIVE_ENTRY_ACL_GROUP_OBJ, ACL_GROUP_OBJ },
551 { ARCHIVE_ENTRY_ACL_MASK, ACL_MASK },
552 { ARCHIVE_ENTRY_ACL_OTHER, ACL_OTHER },
553 };
554
555 acl_tag_t ntag = ACL_UNDEFINED_TAG;
556 FOREACH_ELEMENT(t, tag_map)
557 if (t->libarchive == tag) {
558 ntag = t->libacl;
559 break;
560 }
561 if (ntag == ACL_UNDEFINED_TAG)
562 continue;
563
564 #if HAVE_ACL
565 acl_entry_t e;
566 if (IN_SET(ntag, ACL_USER, ACL_GROUP)) {
567 id_t id = qual;
568 /* Suppress ACL entries for invalid UIDs/GIDS */
569 if (!uid_is_valid(id))
570 continue;
571
572 /* Suppress ACL entries for UIDs/GIDs to squash */
573 if (FLAGS_SET(flags, TAR_SQUASH_UIDS_ABOVE_64K) && id >= NSRESOURCE_UIDS_64K)
574 continue;
575
576 if (sym_acl_create_entry(&a, &e) < 0)
577 return log_error_errno(errno, "Failed to create ACL entry: %m");
578
579 if (sym_acl_set_tag_type(e, ntag) < 0)
580 return log_error_errno(errno, "Failed to set ACL entry tag: %m");
581
582 if (sym_acl_set_qualifier(e, &id) < 0)
583 return log_error_errno(errno, "Failed to set ACL entry qualifier: %m");
584 } else {
585 if (sym_acl_create_entry(&a, &e) < 0)
586 return log_error_errno(errno, "Failed to create ACL entry: %m");
587
588 if (sym_acl_set_tag_type(e, ntag) < 0)
589 return log_error_errno(errno, "Failed to set ACL entry tag: %m");
590 }
591
592 acl_permset_t p;
593 if (sym_acl_get_permset(e, &p) < 0)
594 return log_error_errno(errno, "Failed to get ACL entry permission set: %m");
595
596 r = acl_set_perm(p, ACL_READ, permset & ARCHIVE_ENTRY_ACL_READ);
597 if (r < 0)
598 return log_error_errno(r, "Failed to set ACL entry read bit: %m");
599
600 r = acl_set_perm(p, ACL_WRITE, permset & ARCHIVE_ENTRY_ACL_WRITE);
601 if (r < 0)
602 return log_error_errno(r, "Failed to set ACL entry write bit: %m");
603
604 r = acl_set_perm(p, ACL_EXECUTE, permset & ARCHIVE_ENTRY_ACL_EXECUTE);
605 if (r < 0)
606 return log_error_errno(r, "Failed to set ACL entry execute bit: %m");
607
608 if (sym_acl_set_permset(e, p) < 0)
609 return log_error_errno(errno, "Failed to set ACL entry permission set: %m");
610 #else
611 *acl = POINTER_MAX; /* Indicate the entry has valid ACLs. */
612 return 0;
613 #endif
614 }
615
616 #if HAVE_ACL
617 if (*acl)
618 sym_acl_free(*acl);
619 *acl = TAKE_PTR(a);
620 #else
621 *acl = NULL; /* Indicate the entry has no ACL. */
622 #endif
623 return 0;
624 }
625
626 static uid_t maybe_squash_uid(uid_t uid, TarFlags flags) {
627 if (FLAGS_SET(flags, TAR_SQUASH_UIDS_ABOVE_64K) &&
628 uid_is_valid(uid) &&
629 uid >= NSRESOURCE_UIDS_64K)
630 return UID_NOBODY;
631
632 return uid;
633 }
634
635 static uid_t maybe_squash_gid(uid_t gid, TarFlags flags) {
636 if (FLAGS_SET(flags, TAR_SQUASH_UIDS_ABOVE_64K) &&
637 gid_is_valid(gid) &&
638 gid >= NSRESOURCE_UIDS_64K)
639 return GID_NOBODY;
640
641 return gid;
642 }
643
644 static int archive_entry_read_stat(
645 struct archive_entry *entry,
646 mode_t *filetype,
647 mode_t *mode,
648 struct timespec *mtime,
649 uid_t *uid,
650 gid_t *gid,
651 unsigned *fflags,
652 acl_t *acl_access,
653 acl_t *acl_default,
654 XAttr **xa,
655 size_t *n_xa,
656 TarFlags flags) {
657
658 int r;
659
660 assert(entry);
661 assert(xa);
662 assert(n_xa);
663
664 /* Fills in all fields that are present in the archive entry. Doesn't change the fields if the entry
665 * doesn't contain the relevant data */
666
667 if (filetype)
668 *filetype = sym_archive_entry_filetype(entry);
669
670 if (mode)
671 *mode = sym_archive_entry_mode(entry);
672
673 if (mtime && sym_archive_entry_mtime_is_set(entry))
674 *mtime = (struct timespec) {
675 sym_archive_entry_mtime(entry),
676 sym_archive_entry_mtime_nsec(entry),
677 };
678 if (uid && sym_archive_entry_uid_is_set(entry))
679 *uid = maybe_squash_uid(sym_archive_entry_uid(entry), flags);
680 if (gid && sym_archive_entry_gid_is_set(entry))
681 *gid = maybe_squash_gid(sym_archive_entry_gid(entry), flags);
682
683 if (fflags) {
684 unsigned long fs = 0, fc = 0;
685 sym_archive_entry_fflags(entry, &fs, &fc);
686 *fflags = (fs & ~fc) & CHATTR_TAR_FL;
687 }
688
689 (void) sym_archive_entry_xattr_reset(entry);
690 for (;;) {
691 const char *name = NULL;
692 struct iovec data;
693 r = sym_archive_entry_xattr_next(entry, &name, (const void**) &data.iov_base, &data.iov_len);
694 if (r != ARCHIVE_OK)
695 break;
696
697 assert(name);
698 if (xattr_is_acl(name))
699 continue;
700
701 if (!FLAGS_SET(flags, TAR_SELINUX) && xattr_is_selinux(name))
702 continue;
703
704 bool duplicate = false;
705 FOREACH_ARRAY(i, *xa, *n_xa)
706 if (streq(i->name, name)) {
707 duplicate = true;
708 break;
709 }
710 if (duplicate)
711 continue;
712
713 _cleanup_free_ char *n = strdup(name);
714 if (!n)
715 return log_oom();
716
717 _cleanup_(iovec_done) struct iovec iovec_copy = {};
718 if (!iovec_memdup(&data, &iovec_copy))
719 return log_oom();
720
721 if (!GREEDY_REALLOC(*xa, *n_xa+1))
722 return log_oom();
723
724 (*xa)[(*n_xa)++] = (XAttr) {
725 .name = TAKE_PTR(n),
726 .data = TAKE_STRUCT(iovec_copy),
727 };
728 }
729
730 if (acl_access) {
731 r = archive_entry_read_acl(entry, ACL_TYPE_ACCESS, acl_access, flags);
732 if (r < 0)
733 return r;
734 }
735
736 if (acl_default) {
737 r = archive_entry_read_acl(entry, ACL_TYPE_DEFAULT, acl_default, flags);
738 if (r < 0)
739 return r;
740 }
741
742 return 0;
743 }
744
745 int tar_x(int input_fd, int tree_fd, TarFlags flags) {
746 int ar, r;
747
748 assert(input_fd >= 0);
749 assert(tree_fd >= 0);
750
751 _cleanup_(archive_read_freep) struct archive *a = NULL;
752 a = sym_archive_read_new();
753 if (!a)
754 return log_oom();
755
756 ar = sym_archive_read_support_format_tar(a);
757 if (ar != ARCHIVE_OK)
758 return log_error_errno(
759 SYNTHETIC_ERRNO(ENOTRECOVERABLE),
760 "Failed to enable tar unpacking: %s", sym_archive_error_string(a));
761
762 ar = sym_archive_read_support_format_cpio(a);
763 if (ar != ARCHIVE_OK)
764 return log_error_errno(
765 SYNTHETIC_ERRNO(ENOTRECOVERABLE),
766 "Failed to enable cpio unpacking: %s", sym_archive_error_string(a));
767
768 ar = sym_archive_read_open_fd(a, input_fd, 64 * 1024);
769 if (ar != ARCHIVE_OK)
770 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
771 "Failed to initialize archive context: %s", sym_archive_error_string(a));
772
773
774 OpenInode *open_inodes = NULL;
775 if (!GREEDY_REALLOC(open_inodes, 2)) /* the minimal case is a single file in an archive, which would
776 * mean two inodes, the root dir inode, and he regular file
777 * inode, hence start with 2 here */
778 return log_oom();
779
780 size_t n_open_inodes = 0;
781 CLEANUP_ARRAY(open_inodes, n_open_inodes, open_inode_free_array);
782
783 /* Fill in the root inode. (Note: we leave the .path field as NULL to mark it as root inode.) */
784 open_inodes[0] = (OpenInode) {
785 .fd = tree_fd,
786 .filetype = S_IFDIR,
787 .mode = MODE_INVALID,
788 .mtime = { .tv_nsec = UTIME_OMIT },
789 .uid = UID_INVALID,
790 .gid = GID_INVALID,
791 };
792 n_open_inodes = 1;
793
794 for (;;) {
795 struct archive_entry *entry = NULL;
796
797 ar = sym_archive_read_next_header(a, &entry);
798 if (ar == ARCHIVE_EOF)
799 break;
800 if (!IN_SET(ar, ARCHIVE_OK, ARCHIVE_WARN))
801 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to parse archive: %s",
802 sym_archive_error_string(a));
803
804 const char *p = NULL;
805 r = archive_entry_pathname_safe(entry, &p);
806 if (r < 0)
807 return log_error_errno(r, "Invalid path name in entry, refusing.");
808 if (ar == ARCHIVE_WARN)
809 log_warning("Non-critical error found while parsing '%s' from the archive, ignoring: %s",
810 p ?: ".", sym_archive_error_string(a));
811
812 if (!p) {
813 /* This is the root inode */
814 r = archive_entry_read_stat(
815 entry,
816 &open_inodes[0].filetype,
817 &open_inodes[0].mode,
818 &open_inodes[0].mtime,
819 &open_inodes[0].uid,
820 &open_inodes[0].gid,
821 &open_inodes[0].fflags,
822 &open_inodes[0].acl_access,
823 &open_inodes[0].acl_default,
824 &open_inodes[0].xattr,
825 &open_inodes[0].n_xattr,
826 flags);
827 if (r < 0)
828 return r;
829 if (open_inodes[0].filetype != S_IFDIR)
830 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
831 "Archives root inode is not a directory, refusing.");
832
833 continue;
834 }
835
836 /* Find common prefix with path elements we were looking at so far. */
837 const char *rest = p;
838 size_t i;
839 for (i = 1; i < n_open_inodes; i++) {
840 const char *e = path_startswith(p, open_inodes[i].path);
841 if (isempty(e))
842 break;
843
844 rest = e;
845 }
846
847 /* Finalize all inodes we won't need anymore now (go backwards, i.e. close inner fds first) */
848 while (n_open_inodes > i) {
849 r = open_inode_finalize(open_inodes + n_open_inodes - 1);
850 if (r < 0)
851 return r;
852
853 n_open_inodes--;
854 }
855
856 /* And now create all remaining components */
857 for (;;) {
858 const char *element;
859
860 r = path_find_first_component(&rest, /* accept_dot_dot= */ false, &element);
861 if (r < 0)
862 return log_error_errno(r, "Failed to extract next element from path: %m");
863 if (r == 0)
864 break;
865
866 /* Safety check, before we add another level to our stack */
867 if (n_open_inodes >= DEPTH_MAX)
868 return log_error_errno(
869 SYNTHETIC_ERRNO(E2BIG),
870 "Archive's directory tree nested too deeply, refusing to descend more than %u levels.", DEPTH_MAX);
871
872 _cleanup_free_ char *e = strndup(element, r);
873 if (!e)
874 return log_oom();
875
876 const char *parent_path = NULL;
877 int parent_fd = -EBADF;
878 assert(n_open_inodes > 0);
879 parent_fd = open_inodes[n_open_inodes-1].fd;
880 parent_path = open_inodes[n_open_inodes-1].path;
881
882 _cleanup_free_ char *j = parent_path ? path_join(parent_path, e) : strdup(e);
883 if (!j)
884 return log_oom();
885
886 if (!GREEDY_REALLOC(open_inodes, n_open_inodes+1))
887 return log_oom();
888
889 _cleanup_close_ int fd = -EBADF;
890 mode_t filetype = MODE_INVALID;
891 mode_t mode = MODE_INVALID;
892 uid_t uid = UID_INVALID;
893 gid_t gid = GID_INVALID;
894 struct timespec mtime = { .tv_nsec = UTIME_OMIT };
895 unsigned fflags = 0;
896 #if HAVE_ACL
897 _cleanup_(acl_freep)
898 #endif
899 acl_t acl_access = NULL, acl_default = NULL;
900 XAttr *xa = NULL;
901 size_t n_xa = 0;
902 CLEANUP_ARRAY(xa, n_xa, xattr_free_array);
903
904 if (isempty(rest)) {
905 /* This is the final node in the path, create it */
906
907 if (sym_archive_entry_hardlink_is_set(entry)) {
908 /* If this is a hardlink, act on it */
909 const char *h = sym_archive_entry_hardlink(entry);
910 if (!h)
911 return log_error_errno(
912 SYNTHETIC_ERRNO(EBADMSG),
913 "No hardlink target in hardlink entry, refusing.");
914
915 /* libarchive prefixes all paths with "./", let's chop that off */
916 const char *target = startswith(h, "./") ?: h;
917 if (!path_is_safe(target))
918 return log_error_errno(
919 SYNTHETIC_ERRNO(EBADMSG),
920 "Invalid hardlink path name '%s' in entry, refusing.", target);
921
922 _cleanup_close_ int target_fd = -EBADF;
923 r = chaseat(tree_fd, tree_fd, target,
924 CHASE_PROHIBIT_SYMLINKS|CHASE_NOFOLLOW,
925 /* ret_path= */ NULL, &target_fd);
926 if (r < 0)
927 return log_error_errno(
928 r,
929 "Failed to find inode '%s' which shall be hardlinked as '%s': %m", target, j);
930
931 struct stat verify_st;
932 if (fstat(target_fd, &verify_st) < 0)
933 return log_error_errno(errno, "Failed to stat inode '%s': %m", target);
934
935 /* Refuse hardlinking directories early. */
936 if (!inode_type_can_hardlink(verify_st.st_mode))
937 return log_error_errno(SYNTHETIC_ERRNO(EBADF),
938 "Refusing to hardlink inode '%s' of type '%s': %m",
939 target, inode_type_to_string(verify_st.st_mode));
940
941 if (linkat(target_fd, "", parent_fd, e, AT_EMPTY_PATH) < 0) {
942 if (errno != ENOENT)
943 return log_error_errno(
944 errno,
945 "Failed to hardlink inode '%s' as '%s': %m", target, j);
946
947 /* To be able to link by inode fd we might have needed
948 * CAP_DAC_READ_SEARCH which we lacked. Let's retry with the
949 * parent. Yes, glibc/kernel report this as ENOENT. Kinda
950 * annoying. */
951
952 _cleanup_close_ int target_parent_fd = -EBADF;
953 _cleanup_free_ char *target_filename = NULL;
954 r = chaseat(tree_fd, tree_fd, target,
955 CHASE_PROHIBIT_SYMLINKS|CHASE_PARENT|CHASE_EXTRACT_FILENAME|CHASE_NOFOLLOW,
956 &target_filename, &target_parent_fd);
957 if (r < 0)
958 return log_error_errno(r, "Failed to find inode '%s' which shall be hardlinked as '%s': %m",
959 target, j);
960
961 if (linkat(target_parent_fd, target_filename, parent_fd, e, /* flags= */ 0) < 0)
962 return log_error_errno(errno, "Failed to hardlink inode '%s' as '%s': %m",
963 target, j);
964 }
965
966 continue;
967 }
968
969 r = archive_entry_read_stat(
970 entry,
971 &filetype,
972 &mode,
973 &mtime,
974 &uid,
975 &gid,
976 &fflags,
977 &acl_access,
978 &acl_default,
979 &xa,
980 &n_xa,
981 flags);
982 if (r < 0)
983 return r;
984
985 switch (filetype) {
986
987 case S_IFREG:
988 if (FLAGS_SET(flags, TAR_OCI_WHITEOUTS)) {
989 if (streq(e, ".wh..wh..opq")) {
990 r = archive_unpack_opaque(a, entry, parent_fd, empty_to_root(parent_path));
991 if (r < 0)
992 return r;
993
994 /* NB: this does not create an inode! */
995 break;
996 }
997
998 const char *w = startswith(e, ".wh.");
999 if (w) {
1000 if (!filename_is_valid(w))
1001 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
1002 "Invalid whiteout file entry '%s', refusing.", e);
1003
1004 r = archive_unpack_whiteout(a, entry, parent_fd, empty_to_root(parent_path), w, j);
1005 if (r < 0)
1006 return r;
1007
1008 /* NB: this does not create an inode! */
1009 break;
1010 }
1011 }
1012
1013 fd = archive_unpack_regular(a, entry, parent_fd, e, j, fflags);
1014 if (fd < 0)
1015 return fd;
1016 break;
1017
1018 case S_IFDIR:
1019 fd = archive_unpack_directory(a, entry, parent_fd, e, j, fflags);
1020 if (fd < 0)
1021 return fd;
1022 break;
1023
1024 case S_IFLNK:
1025 fd = archive_unpack_symlink(a, entry, parent_fd, e, j);
1026 if (fd < 0)
1027 return fd;
1028 break;
1029
1030 case S_IFCHR:
1031 case S_IFBLK:
1032 case S_IFIFO:
1033 case S_IFSOCK:
1034 fd = archive_unpack_special_inode(a, entry, parent_fd, e, j, filetype);
1035 if (fd < 0)
1036 return fd;
1037 break;
1038
1039 default:
1040 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1041 "Unexpected file type %i of '%s', refusing.",
1042 (int) filetype, j);
1043 }
1044 } else {
1045 /* This is some intermediary node in the path that we haven't opened yet. Create it with default attributes */
1046 fd = open_mkdir_at(parent_fd, e, O_CLOEXEC, 0700);
1047 if (fd < 0)
1048 return log_error_errno(fd, "Failed to create directory '%s': %m", j);
1049
1050 filetype = S_IFDIR;
1051 }
1052
1053 /* Now store a reference to the inode we just created in our stack array. Note that
1054 * we have not applied file ownership, access mode, mtime here, we'll do that only
1055 * when we are finished with the inode, since we have to apply them *after* we are
1056 * fully done with the inode (i.e. after creating further inodes inside of dir inodes
1057 * for example), due to permission problems this might create or that the mtime
1058 * changes we do might still be affected by our changes. */
1059 if (fd >= 0) {
1060 open_inodes[n_open_inodes++] = (OpenInode) {
1061 .fd = TAKE_FD(fd),
1062 .path = TAKE_PTR(j),
1063 .filetype = filetype,
1064 .mode = mode,
1065 .mtime = mtime,
1066 .uid = uid,
1067 .gid = gid,
1068 .fflags = fflags,
1069 .acl_access = TAKE_PTR(acl_access),
1070 .acl_default = TAKE_PTR(acl_default),
1071 .xattr = TAKE_PTR(xa),
1072 .n_xattr = n_xa,
1073 };
1074
1075 n_xa = 0;
1076 }
1077 }
1078 }
1079
1080 r = open_inode_finalize_many(&open_inodes, &n_open_inodes);
1081 if (r < 0)
1082 return r;
1083
1084 return 0;
1085 }
1086
1087 static int make_tmpfs(void) {
1088 /* Creates a tmpfs superblock to store our hardlink db in. We can do this if we run in our own
1089 * userns, or if we are privileged. This is preferable, since it means the db is cleaned up
1090 * automatically once we are done. Moreover, since this is a new superblock owned by us, we do not
1091 * need to set up any uid mapping shenanigans */
1092
1093 _cleanup_close_ int superblock_fd = fsopen("tmpfs", FSOPEN_CLOEXEC);
1094 if (superblock_fd < 0)
1095 return log_debug_errno(errno, "Failed to allocate tmpfs superblock: %m");
1096
1097 (void) fsconfig(superblock_fd, FSCONFIG_SET_STRING, "source", "hardlink", /* aux= */ 0);
1098 (void) fsconfig(superblock_fd, FSCONFIG_SET_STRING, "mode", "0700", /* aux= */ 0);
1099
1100 if (fsconfig(superblock_fd, FSCONFIG_CMD_CREATE, /* key= */ NULL, /* value= */ NULL, /* aux= */ 0) < 0)
1101 return log_debug_errno(errno, "Failed to finalize superblock: %m");
1102
1103 _cleanup_close_ int mount_fd = fsmount(superblock_fd, FSMOUNT_CLOEXEC, MS_NODEV|MS_NOEXEC|MS_NOSUID);
1104 if (mount_fd < 0)
1105 return log_debug_errno(errno, "Failed to turn tmpfs superblock into mount: %m");
1106
1107 return TAKE_FD(mount_fd);
1108 }
1109
1110 struct make_archive_data {
1111 struct archive *archive;
1112 TarFlags flags;
1113
1114 int hardlink_db_fd;
1115 char *hardlink_db_path;
1116 int have_unique_mount_id;
1117 };
1118
1119 static int filter_item(
1120 int inode_fd,
1121 const struct statx *sx,
1122 const char *path) {
1123 mode_t m;
1124 int r;
1125
1126 assert(inode_fd >= 0);
1127 assert(sx);
1128 assert(path);
1129
1130 if (FLAGS_SET(sx->stx_mask, STATX_TYPE))
1131 m = sx->stx_mode;
1132 else {
1133 struct stat st;
1134 r = RET_NERRNO(fstat(inode_fd, &st));
1135 if (r < 0)
1136 return log_error_errno(r, "Failed to stat '%s': %m", path);
1137 m = st.st_mode;
1138 }
1139
1140 /* Filter out sockets, fifos, and weird misc fds such as eventfds() that have no inode type. */
1141 if (IN_SET(m & S_IFMT, S_IFSOCK, S_IFIFO, 0)) {
1142 log_debug("Skipping '%s' (%s).", path, inode_type_to_string(m) ?: "unknown");
1143 return false;
1144 }
1145
1146 return true;
1147 }
1148
1149 static int hardlink_lookup(
1150 struct make_archive_data *d,
1151 int inode_fd,
1152 const struct statx *sx,
1153 const char *path,
1154 char **ret) {
1155
1156 _cleanup_free_ struct file_handle *handle = NULL;
1157 _cleanup_free_ char *m = NULL, *n = NULL;
1158 int r;
1159
1160 assert(d);
1161 assert(inode_fd >= 0);
1162 assert(sx);
1163 assert(ret);
1164
1165 /* If we know the hardlink count, and it's 1, then don't bother */
1166 if (FLAGS_SET(sx->stx_mask, STATX_NLINK) && sx->stx_nlink == 1)
1167 goto bypass;
1168
1169 /* If this is a directory, then don't bother */
1170 if (FLAGS_SET(sx->stx_mask, STATX_TYPE) && !inode_type_can_hardlink(sx->stx_mode))
1171 goto bypass;
1172
1173 uint64_t unique_mnt_id;
1174 int mnt_id;
1175 r = name_to_handle_at_try_fid(inode_fd, /* path= */ NULL,
1176 &handle,
1177 d->have_unique_mount_id <= 0 ? &mnt_id : NULL,
1178 d->have_unique_mount_id != 0 ? &unique_mnt_id : NULL,
1179 /* flags= */ AT_EMPTY_PATH);
1180 if (r < 0)
1181 return log_error_errno(r, "Failed to get file handle of file: %m");
1182 if (d->have_unique_mount_id < 0)
1183 d->have_unique_mount_id = r > 0;
1184 else
1185 assert(d->have_unique_mount_id == (r > 0));
1186
1187 m = hexmem(SHA256_DIRECT(handle->f_handle, handle->handle_bytes), SHA256_DIGEST_SIZE);
1188 if (!m)
1189 return log_oom();
1190
1191 if (d->have_unique_mount_id)
1192 r = asprintf(&n, "%" PRIu64 ":%i:%s", unique_mnt_id, handle->handle_type, m);
1193 else
1194 r = asprintf(&n, "%i:%i:%s", mnt_id, handle->handle_type, m);
1195 if (r < 0)
1196 return log_oom();
1197
1198 if (d->hardlink_db_fd < 0) {
1199 assert(!d->hardlink_db_path);
1200
1201 /* We first try to create our own superblock, which works if we are in a userns, and which
1202 * doesn't require explicit clean-up */
1203 d->hardlink_db_fd = make_tmpfs();
1204 if (d->hardlink_db_fd < 0) {
1205 log_debug_errno(d->hardlink_db_fd, "Failed to allocate tmpfs superblock for hardlink db, falling back to temporary directory: %m");
1206
1207 const char *vt;
1208 r = var_tmp_dir(&vt);
1209 if (r < 0)
1210 return log_error_errno(r, "Failed to determine /var/tmp/ directory: %m");
1211
1212 _cleanup_free_ char *j = path_join(vt, "make-tar-XXXXXX");
1213 if (!j)
1214 return log_oom();
1215
1216 d->hardlink_db_fd = mkdtemp_open(j, /* flags= */ 0, &d->hardlink_db_path);
1217 if (d->hardlink_db_fd < 0)
1218 return log_error_errno(d->hardlink_db_fd, "Failed to make hardlink database directory: %m");
1219 }
1220 } else {
1221 _cleanup_free_ char *p = NULL;
1222 r = readlinkat_malloc(d->hardlink_db_fd, n, &p);
1223 if (r >= 0) {
1224 /* Found previous hit! */
1225 log_debug("hardlinkdb: found %s → %s", n, p);
1226 *ret = TAKE_PTR(p);
1227 return 1;
1228 }
1229 if (r != -ENOENT)
1230 return log_error_errno(r, "Failed to read symlink '%s': %m", n);
1231 }
1232
1233 /* Store information about this inode */
1234 if (symlinkat(path, d->hardlink_db_fd, n) < 0)
1235 return log_error_errno(errno, "Failed to create symlink '%s' → '%s': %m", n, path);
1236
1237 log_debug("hardlinkdb: created %s → %s", n, path);
1238
1239 bypass:
1240 *ret = NULL;
1241 return 0;
1242 }
1243
1244 static int archive_generate_sparse(struct archive_entry *entry, int fd) {
1245 assert(entry);
1246 assert(fd);
1247
1248 off_t c = 0;
1249 for (;;) {
1250 /* Look for the next hole */
1251 off_t h = lseek(fd, c, SEEK_HOLE);
1252 if (h < 0) {
1253 if (errno != ENXIO)
1254 return log_error_errno(errno, "Failed to issue SEEK_HOLE: %m");
1255
1256 /* If errno == ENXIO, that means we've reached the final data of the file and
1257 * that data isn't followed by anything more */
1258
1259 /* Figure out where the end of the file is */
1260 off_t e = lseek(fd, 0, SEEK_END);
1261 if (e < 0)
1262 return log_error_errno(errno, "Failed to issue SEEK_END: %m");
1263
1264 /* Generate sparse entry for final block */
1265 if (e > c && c != 0) {
1266 log_debug("final sparse block %" PRIu64 "…%" PRIu64, (uint64_t) c, (uint64_t) e);
1267 sym_archive_entry_sparse_add_entry(entry, c, e - c);
1268 }
1269
1270 break;
1271 }
1272
1273 if (h > c) {
1274 log_debug("inner sparse block %" PRIu64 "…%" PRIu64 " (%" PRIu64 ")", (uint64_t) c, (uint64_t) h, (uint64_t) h - (uint64_t) c);
1275 sym_archive_entry_sparse_add_entry(entry, c, h - c);
1276 }
1277
1278 /* Now look for the next data after the hole */
1279 c = lseek(fd, h, SEEK_DATA);
1280 if (c < 0) {
1281 if (errno != ENXIO)
1282 return log_error_errno(errno, "Failed to issue SEEK_DATA: %m");
1283
1284 /* No data anymore */
1285 break;
1286 }
1287 }
1288
1289 if (lseek(fd, 0, SEEK_SET) < 0)
1290 return log_error_errno(errno, "Failed to reset seek offset: %m");
1291
1292 return 0;
1293 }
1294
1295 #if HAVE_ACL
1296 static int archive_write_acl(
1297 struct archive_entry *entry,
1298 acl_type_t ntype,
1299 acl_t acl,
1300 TarFlags flags) {
1301 int r;
1302
1303 assert(entry);
1304 assert(acl);
1305
1306 int type;
1307 if (ntype == ACL_TYPE_ACCESS)
1308 type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
1309 else if (ntype == ACL_TYPE_DEFAULT)
1310 type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT;
1311 else
1312 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unexpected ACL type");
1313
1314 acl_entry_t e;
1315 r = sym_acl_get_entry(acl, ACL_FIRST_ENTRY, &e);
1316 for (;;) {
1317 if (r < 0)
1318 return log_error_errno(errno, "Failed to get ACL entry: %m");
1319 if (r == 0)
1320 break;
1321
1322 acl_tag_t ntag;
1323 if (sym_acl_get_tag_type(e, &ntag) < 0)
1324 return log_error_errno(errno, "Failed to get ACL entry tag: %m");
1325
1326 static const int tag_map[] = {
1327 [ACL_USER] = ARCHIVE_ENTRY_ACL_USER,
1328 [ACL_GROUP] = ARCHIVE_ENTRY_ACL_GROUP,
1329 [ACL_USER_OBJ] = ARCHIVE_ENTRY_ACL_USER_OBJ,
1330 [ACL_GROUP_OBJ] = ARCHIVE_ENTRY_ACL_GROUP_OBJ,
1331 [ACL_MASK] = ARCHIVE_ENTRY_ACL_MASK,
1332 [ACL_OTHER] = ARCHIVE_ENTRY_ACL_OTHER,
1333 };
1334 assert_cc(ACL_UNDEFINED_TAG == 0); /* safety check, we assume that holes are filled with ACL_UNDEFINED_TAG */
1335 assert_cc(ELEMENTSOF(tag_map) <= 64); /* safety check, we assume that the tag ids are all packed and low */
1336
1337 int tag = ntag >= 0 && ntag <= (acl_tag_t) ELEMENTSOF(tag_map) ? tag_map[ntag] : ACL_UNDEFINED_TAG;
1338
1339 bool skip = false;
1340 id_t qualifier = UID_INVALID;
1341 if (IN_SET(ntag, ACL_USER, ACL_GROUP)) {
1342 id_t *q = sym_acl_get_qualifier(e);
1343 if (!q)
1344 return log_error_errno(errno, "Failed to get ACL entry qualifier: %m");
1345
1346 qualifier = *q;
1347 sym_acl_free(q);
1348
1349 /* Suppress invalid UIDs or those that shall be squashed */
1350 skip = !(uid_is_valid(qualifier) &&
1351 (!FLAGS_SET(flags, TAR_SQUASH_UIDS_ABOVE_64K) || qualifier < NSRESOURCE_UIDS_64K));
1352 }
1353
1354 if (!skip) {
1355 acl_permset_t p;
1356 if (sym_acl_get_permset(e, &p) < 0)
1357 return log_error_errno(errno, "Failed to get ACL entry permission set: %m");
1358
1359 int permset = 0;
1360 r = sym_acl_get_perm(p, ACL_READ);
1361 if (r < 0)
1362 return log_error_errno(r, "Failed to get ACL entry read bit: %m");
1363 SET_FLAG(permset, ARCHIVE_ENTRY_ACL_READ, r);
1364
1365 r = sym_acl_get_perm(p, ACL_WRITE);
1366 if (r < 0)
1367 return log_error_errno(r, "Failed to get ACL entry write bit: %m");
1368 SET_FLAG(permset, ARCHIVE_ENTRY_ACL_WRITE, r);
1369
1370 r = sym_acl_get_perm(p, ACL_EXECUTE);
1371 if (r < 0)
1372 return log_error_errno(r, "Failed to get ACL entry execute bit: %m");
1373 SET_FLAG(permset, ARCHIVE_ENTRY_ACL_EXECUTE, r);
1374
1375 r = sym_archive_entry_acl_add_entry(entry, type, permset, tag, qualifier, /* name= */ NULL);
1376 if (r != ARCHIVE_OK)
1377 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to add ACL entry.");
1378 }
1379
1380 r = sym_acl_get_entry(acl, ACL_NEXT_ENTRY, &e);
1381 }
1382
1383 return 0;
1384 }
1385 #endif
1386
1387 static int archive_item(
1388 RecurseDirEvent event,
1389 const char *path,
1390 int dir_fd,
1391 int inode_fd,
1392 const struct dirent *de,
1393 const struct statx *sx,
1394 void *userdata) {
1395
1396 struct make_archive_data *d = ASSERT_PTR(userdata);
1397 int r;
1398
1399 assert(path);
1400
1401 if (!IN_SET(event, RECURSE_DIR_ENTER, RECURSE_DIR_ENTRY))
1402 return RECURSE_DIR_CONTINUE;
1403
1404 assert(inode_fd >= 0);
1405 assert(sx);
1406
1407 r = filter_item(inode_fd, sx, path);
1408 if (r < 0)
1409 return r;
1410 if (r == 0)
1411 return RECURSE_DIR_CONTINUE;
1412
1413 log_debug("Archiving '%s'...", path);
1414
1415 _cleanup_(archive_entry_freep) struct archive_entry *entry = NULL;
1416 entry = sym_archive_entry_new();
1417 if (!entry)
1418 return log_oom();
1419
1420 sym_archive_entry_set_pathname(entry, path);
1421
1422 _cleanup_free_ char *hardlink = NULL;
1423 r = hardlink_lookup(d, inode_fd, sx, path, &hardlink);
1424 if (r < 0)
1425 return r;
1426 if (r > 0) {
1427 sym_archive_entry_set_hardlink(entry, hardlink);
1428
1429 if (sym_archive_write_header(d->archive, entry) != ARCHIVE_OK)
1430 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1431 "Failed to write archive entry header: %s", sym_archive_error_string(d->archive));
1432
1433 return RECURSE_DIR_CONTINUE;
1434 }
1435
1436 assert(FLAGS_SET(sx->stx_mask, STATX_TYPE|STATX_MODE));
1437 sym_archive_entry_set_filetype(entry, sx->stx_mode);
1438
1439 if (!S_ISLNK(sx->stx_mode))
1440 sym_archive_entry_set_perm(entry, sx->stx_mode);
1441
1442 if (FLAGS_SET(sx->stx_mask, STATX_UID))
1443 sym_archive_entry_set_uid(entry, maybe_squash_uid(sx->stx_uid, d->flags));
1444 if (FLAGS_SET(sx->stx_mask, STATX_GID))
1445 sym_archive_entry_set_gid(entry, maybe_squash_gid(sx->stx_gid, d->flags));
1446
1447 if (S_ISREG(sx->stx_mode)) {
1448 if (!FLAGS_SET(sx->stx_mask, STATX_SIZE))
1449 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Unable to determine file size of '%s'.", path);
1450
1451 sym_archive_entry_set_size(entry, sx->stx_size);
1452 }
1453
1454 if (S_ISCHR(sx->stx_mode) || S_ISBLK(sx->stx_mode)) {
1455 sym_archive_entry_set_rdevmajor(entry, sx->stx_rdev_major);
1456 sym_archive_entry_set_rdevminor(entry, sx->stx_rdev_minor);
1457 }
1458
1459 /* We care about a modicum of reproducibility here, hence we don't save atime/btime here */
1460 if (FLAGS_SET(sx->stx_mask, STATX_MTIME))
1461 sym_archive_entry_set_mtime(entry, sx->stx_mtime.tv_sec, sx->stx_mtime.tv_nsec);
1462 if (FLAGS_SET(sx->stx_mask, STATX_CTIME))
1463 sym_archive_entry_set_ctime(entry, sx->stx_ctime.tv_sec, sx->stx_ctime.tv_nsec);
1464
1465 if (S_ISLNK(sx->stx_mode)) {
1466 _cleanup_free_ char *s = NULL;
1467
1468 assert(dir_fd >= 0);
1469 assert(de);
1470
1471 r = readlinkat_malloc(dir_fd, de->d_name, &s);
1472 if (r < 0)
1473 return log_error_errno(r, "Failed to read symlink target of '%s': %m", path);
1474
1475 sym_archive_entry_set_symlink(entry, s);
1476 }
1477
1478 #if HAVE_ACL
1479 if (inode_type_can_acl(sx->stx_mode)) {
1480
1481 r = dlopen_libacl(LOG_DEBUG);
1482 if (r >= 0) {
1483 r = sym_acl_extended_file(FORMAT_PROC_FD_PATH(inode_fd));
1484 if (r < 0 && !ERRNO_IS_NOT_SUPPORTED(errno))
1485 return log_error_errno(errno, "Failed check if '%s' has ACLs: %m", path);
1486 if (r > 0) {
1487 _cleanup_(acl_freep) acl_t acl = NULL;
1488 acl = sym_acl_get_file(FORMAT_PROC_FD_PATH(inode_fd), ACL_TYPE_ACCESS);
1489 if (!acl)
1490 return log_error_errno(errno, "Failed read access ACLs of '%s': %m", path);
1491
1492 archive_write_acl(entry, ACL_TYPE_ACCESS, acl, d->flags);
1493
1494 if (S_ISDIR(sx->stx_mode)) {
1495 sym_acl_free(acl);
1496
1497 acl = sym_acl_get_file(FORMAT_PROC_FD_PATH(inode_fd), ACL_TYPE_DEFAULT);
1498 if (!acl)
1499 return log_error_errno(errno, "Failed to read default ACLs of '%s': %m", path);
1500
1501 archive_write_acl(entry, ACL_TYPE_DEFAULT, acl, d->flags);
1502 }
1503 }
1504 }
1505 }
1506 #endif
1507
1508 _cleanup_free_ char *xattrs = NULL;
1509 r = flistxattr_malloc(inode_fd, &xattrs);
1510 if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r) && r != -ENODATA)
1511 return log_error_errno(r, "Failed to read xattr list of '%s': %m", path);
1512
1513 NULSTR_FOREACH(xa, xattrs) {
1514 _cleanup_free_ char *buf = NULL;
1515 size_t size;
1516
1517 if (xattr_is_acl(xa))
1518 continue;
1519
1520 if (!FLAGS_SET(d->flags, TAR_SELINUX) && xattr_is_selinux(xa))
1521 continue;
1522
1523 r = fgetxattr_malloc(inode_fd, xa, &buf, &size);
1524 if (r == -ENODATA) /* deleted by now? ignore... */
1525 continue;
1526 if (r < 0)
1527 return log_error_errno(r, "Failed to read xattr '%s' of '%s': %m", xa, path);
1528
1529 sym_archive_entry_xattr_add_entry(entry, xa, buf, size);
1530 }
1531
1532 _cleanup_close_ int data_fd = -EBADF;
1533 if (S_ISREG(sx->stx_mode)) {
1534 /* Convert the O_PATH fd into a proper fd */
1535 data_fd = fd_reopen(inode_fd, O_RDONLY|O_CLOEXEC);
1536 if (data_fd < 0)
1537 return log_error_errno(data_fd, "Failed to open '%s': %m", path);
1538
1539 r = archive_generate_sparse(entry, data_fd);
1540 if (r < 0)
1541 return r;
1542 }
1543
1544 if (inode_type_can_chattr(sx->stx_mode)) {
1545 unsigned f = 0;
1546
1547 r = read_attr_fd(data_fd >= 0 ? data_fd : inode_fd, &f);
1548 if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
1549 return log_error_errno(r, "Failed to read file flags of '%s': %m", path);
1550
1551 f &= CHATTR_TAR_FL;
1552 if (f != 0)
1553 sym_archive_entry_set_fflags(entry, f, /* clear= */ 0);
1554 }
1555
1556 if (sym_archive_write_header(d->archive, entry) != ARCHIVE_OK)
1557 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1558 "Failed to write archive entry header: %s",
1559 sym_archive_error_string(d->archive));
1560
1561 if (S_ISREG(sx->stx_mode)) {
1562 assert(data_fd >= 0);
1563
1564 for (;;) {
1565 char buffer[64*1024];
1566 ssize_t l;
1567
1568 l = read(data_fd, buffer, sizeof(buffer));
1569 if (l < 0)
1570 return log_error_errno(errno, "Failed to read '%s': %m", path);
1571 if (l == 0)
1572 break;
1573
1574 la_ssize_t k;
1575 k = sym_archive_write_data(d->archive, buffer, l);
1576 if (k < 0)
1577 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1578 "Failed to write archive data: %s",
1579 sym_archive_error_string(d->archive));
1580 }
1581 }
1582
1583 return RECURSE_DIR_CONTINUE;
1584 }
1585
1586 static void make_archive_data_done(struct make_archive_data *d) {
1587 assert(d);
1588
1589 if (d->hardlink_db_fd >= 0)
1590 (void) rm_rf_children(d->hardlink_db_fd, REMOVE_PHYSICAL, /* root_dev= */ NULL);
1591
1592 unlink_and_free(d->hardlink_db_path);
1593 }
1594
1595 int tar_c(int tree_fd, int output_fd, const char *filename, TarFlags flags) {
1596 int r;
1597
1598 assert(tree_fd >= 0);
1599 assert(output_fd >= 0);
1600
1601 _cleanup_(archive_write_freep) struct archive *a = sym_archive_write_new();
1602 if (!a)
1603 return log_oom();
1604
1605 if (filename)
1606 r = sym_archive_write_set_format_filter_by_ext(a, filename);
1607 else
1608 r = sym_archive_write_set_format_pax(a);
1609 if (r != ARCHIVE_OK)
1610 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1611 "Failed to set libarchive output format: %s", sym_archive_error_string(a));
1612
1613 r = sym_archive_write_open_fd(a, output_fd);
1614 if (r != ARCHIVE_OK)
1615 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1616 "Failed to set libarchive output file: %s", sym_archive_error_string(a));
1617
1618 _cleanup_(make_archive_data_done) struct make_archive_data data = {
1619 .archive = a,
1620 .flags = flags,
1621 .hardlink_db_fd = -EBADF,
1622 .have_unique_mount_id = -1,
1623 };
1624
1625 r = recurse_dir(tree_fd,
1626 ".",
1627 STATX_TYPE|STATX_MODE|STATX_UID|STATX_GID|STATX_SIZE|STATX_ATIME|STATX_CTIME,
1628 UINT_MAX,
1629 RECURSE_DIR_SORT|RECURSE_DIR_INODE_FD|RECURSE_DIR_TOPLEVEL,
1630 archive_item,
1631 &data);
1632 if (r < 0)
1633 return log_error_errno(r, "Failed to make archive: %m");
1634
1635 r = sym_archive_write_close(a);
1636 if (r != ARCHIVE_OK)
1637 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1638 "Unable to finish writing archive: %s", sym_archive_error_string(a));
1639
1640 return 0;
1641 }
1642
1643 #else
1644
1645 int tar_x(int input_fd, int tree_fd, TarFlags flags) {
1646 assert(input_fd >= 0);
1647 assert(tree_fd >= 0);
1648
1649 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "libarchive support not available.");
1650 }
1651
1652 int tar_c(int tree_fd, int output_fd, const char *filename, TarFlags flags) {
1653 assert(tree_fd >= 0);
1654 assert(output_fd >= 0);
1655
1656 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "libarchive support not available.");
1657 }
1658
1659 #endif