2 * Copyright (c) 2003-2010 Tim Kientzle
3 * Copyright (c) 2012 Michihiro NAKAJIMA
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer
11 * in this position and unchanged.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD$");
31 #if !defined(_WIN32) || defined(__CYGWIN__)
33 #ifdef HAVE_SYS_TYPES_H
34 #include <sys/types.h>
39 #ifdef HAVE_SYS_EXTATTR_H
40 #include <sys/extattr.h>
43 #include <sys/xattr.h>
44 #elif HAVE_ATTR_XATTR_H
45 #include <attr/xattr.h>
50 #ifdef HAVE_SYS_IOCTL_H
51 #include <sys/ioctl.h>
53 #ifdef HAVE_SYS_STAT_H
56 #ifdef HAVE_SYS_TIME_H
59 #ifdef HAVE_SYS_UTIME_H
60 #include <sys/utime.h>
62 #ifdef HAVE_COPYFILE_H
74 #ifdef HAVE_LANGINFO_H
77 #ifdef HAVE_LINUX_FS_H
78 #include <linux/fs.h> /* for Linux file flags */
81 * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
82 * As the include guards don't agree, the order of include is important.
84 #ifdef HAVE_LINUX_EXT2_FS_H
85 #include <linux/ext2_fs.h> /* for Linux file flags */
87 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
88 #include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */
109 #ifdef F_GETTIMES /* Tru64 specific */
110 #include <sys/fcntl1.h>
114 * Macro to cast st_mtime and time_t to an int64 so that 2 numbers can reliably be compared.
116 * It assumes that the input is an integer type of no more than 64 bits.
117 * If the number is less than zero, t must be a signed type, so it fits in
118 * int64_t. Otherwise, it's a nonnegative value so we can cast it to uint64_t
119 * without loss. But it could be a large unsigned value, so we have to clip it
122 #define to_int64_time(t) \
123 ((t) < 0 ? (int64_t)(t) : (uint64_t)(t) > (uint64_t)INT64_MAX ? INT64_MAX : (int64_t)(t))
126 #include <TargetConditionals.h>
127 #if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
128 #include <quarantine.h>
129 #define HAVE_QUARANTINE 1
137 /* TODO: Support Mac OS 'quarantine' feature. This is really just a
138 * standard tag to mark files that have been downloaded as "tainted".
139 * On Mac OS, we should mark the extracted files as tainted if the
140 * archive being read was tainted. Windows has a similar feature; we
141 * should investigate ways to support this generically. */
144 #include "archive_acl_private.h"
145 #include "archive_string.h"
146 #include "archive_endian.h"
147 #include "archive_entry.h"
148 #include "archive_private.h"
149 #include "archive_write_disk_private.h"
158 /* Ignore non-int O_NOFOLLOW constant. */
159 /* gnulib's fcntl.h does this on AIX, but it seems practical everywhere */
160 #if defined O_NOFOLLOW && !(INT_MIN <= O_NOFOLLOW && O_NOFOLLOW <= INT_MAX)
169 #define AT_FDCWD -100
173 struct fixup_entry *next;
174 struct archive_acl acl;
180 unsigned long atime_nanos;
181 unsigned long birthtime_nanos;
182 unsigned long mtime_nanos;
183 unsigned long ctime_nanos;
184 unsigned long fflags_set;
185 size_t mac_metadata_size;
187 int fixup; /* bitmask of what needs fixing */
192 * We use a bitmask to track which operations remain to be done for
193 * this file. In particular, this helps us avoid unnecessary
194 * operations when it's possible to take care of one step as a
195 * side-effect of another. For example, mkdir() can specify the mode
196 * for the newly-created object but symlink() cannot. This means we
197 * can skip chmod() if mkdir() succeeded, but we must explicitly
198 * chmod() if we're trying to create a directory that already exists
199 * (mkdir() failed) or if we're restoring a symlink. Similarly, we
200 * need to verify UID/GID before trying to restore SUID/SGID bits;
201 * that verification can occur explicitly through a stat() call or
202 * implicitly because of a successful chown() call.
204 #define TODO_MODE_FORCE 0x40000000
205 #define TODO_MODE_BASE 0x20000000
206 #define TODO_SUID 0x10000000
207 #define TODO_SUID_CHECK 0x08000000
208 #define TODO_SGID 0x04000000
209 #define TODO_SGID_CHECK 0x02000000
210 #define TODO_APPLEDOUBLE 0x01000000
211 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
212 #define TODO_TIMES ARCHIVE_EXTRACT_TIME
213 #define TODO_OWNER ARCHIVE_EXTRACT_OWNER
214 #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
215 #define TODO_ACLS ARCHIVE_EXTRACT_ACL
216 #define TODO_XATTR ARCHIVE_EXTRACT_XATTR
217 #define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA
218 #define TODO_HFS_COMPRESSION ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED
220 struct archive_write_disk {
221 struct archive archive;
224 struct fixup_entry *fixup_list;
225 struct fixup_entry *current_fixup;
228 int64_t skip_file_dev;
229 int64_t skip_file_ino;
232 int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid);
233 void (*cleanup_gid)(void *private);
234 void *lookup_gid_data;
235 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid);
236 void (*cleanup_uid)(void *private);
237 void *lookup_uid_data;
240 * Full path of last file to satisfy symlink checks.
242 struct archive_string path_safe;
245 * Cached stat data from disk for the current entry.
246 * If this is valid, pst points to st. Otherwise,
252 /* Information about the object being restored right now. */
253 struct archive_entry *entry; /* Entry being extracted. */
254 char *name; /* Name of entry, possibly edited. */
255 struct archive_string _name_data; /* backing store for 'name' */
256 /* Tasks remaining for this object. */
258 /* Tasks deferred until end-of-archive. */
260 /* Options requested by the client. */
262 /* Handle for the file we're restoring. */
264 /* Current offset for writing data to the file. */
266 /* Last offset actually written to disk. */
268 /* Total bytes actually written to files. */
269 int64_t total_bytes_written;
270 /* Maximum size of file, -1 if unknown. */
272 /* Dir we were in before this restore; only for deep paths. */
274 /* Mode we should use for this entry; affected by _PERM and umask. */
276 /* UID/GID to use in restoring this entry. */
282 /* Xattr "com.apple.decmpfs". */
283 uint32_t decmpfs_attr_size;
284 unsigned char *decmpfs_header_p;
285 /* ResourceFork set options used for fsetxattr. */
286 int rsrc_xattr_options;
287 /* Xattr "com.apple.ResourceFork". */
288 unsigned char *resource_fork;
289 size_t resource_fork_allocated_size;
290 unsigned int decmpfs_block_count;
291 uint32_t *decmpfs_block_info;
292 /* Buffer for compressed data. */
293 unsigned char *compressed_buffer;
294 size_t compressed_buffer_size;
295 size_t compressed_buffer_remaining;
296 /* The offset of the ResourceFork where compressed data will
298 uint32_t compressed_rsrc_position;
299 uint32_t compressed_rsrc_position_v;
300 /* Buffer for uncompressed data. */
301 char *uncompressed_buffer;
302 size_t block_remaining_bytes;
303 size_t file_remaining_bytes;
307 int decmpfs_compression_level;
312 * Default mode for dirs created automatically (will be modified by umask).
313 * Note that POSIX specifies 0777 for implicitly-created dirs, "modified
314 * by the process' file creation mask."
316 #define DEFAULT_DIR_MODE 0777
318 * Dir modes are restored in two steps: During the extraction, the permissions
319 * in the archive are modified to match the following limits. During
320 * the post-extract fixup pass, the permissions from the archive are
323 #define MINIMUM_DIR_MODE 0700
324 #define MAXIMUM_DIR_MODE 0775
327 * Maximum uncompressed size of a decmpfs block.
329 #define MAX_DECMPFS_BLOCK_SIZE (64 * 1024)
331 * HFS+ compression type.
333 #define CMP_XATTR 3/* Compressed data in xattr. */
334 #define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */
336 * HFS+ compression resource fork.
338 #define RSRC_H_SIZE 260 /* Base size of Resource fork header. */
339 #define RSRC_F_SIZE 50 /* Size of Resource fork footer. */
340 /* Size to write compressed data to resource fork. */
341 #define COMPRESSED_W_SIZE (64 * 1024)
342 /* decmpfs definitions. */
343 #define MAX_DECMPFS_XATTR_SIZE 3802
344 #ifndef DECMPFS_XATTR_NAME
345 #define DECMPFS_XATTR_NAME "com.apple.decmpfs"
347 #define DECMPFS_MAGIC 0x636d7066
348 #define DECMPFS_COMPRESSION_MAGIC 0
349 #define DECMPFS_COMPRESSION_TYPE 4
350 #define DECMPFS_UNCOMPRESSED_SIZE 8
351 #define DECMPFS_HEADER_SIZE 16
353 #define HFS_BLOCKS(s) ((s) >> 12)
356 static int la_opendirat(int, const char *);
357 static void fsobj_error(int *, struct archive_string *, int, const char *,
359 static int check_symlinks_fsobj(char *, int *, struct archive_string *,
361 static int check_symlinks(struct archive_write_disk *);
362 static int create_filesystem_object(struct archive_write_disk *);
363 static struct fixup_entry *current_fixup(struct archive_write_disk *,
364 const char *pathname);
365 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
366 static void edit_deep_directories(struct archive_write_disk *ad);
368 static int cleanup_pathname_fsobj(char *, int *, struct archive_string *,
370 static int cleanup_pathname(struct archive_write_disk *);
371 static int create_dir(struct archive_write_disk *, char *);
372 static int create_parent_dir(struct archive_write_disk *, char *);
373 static ssize_t hfs_write_data_block(struct archive_write_disk *,
374 const char *, size_t);
375 static int fixup_appledouble(struct archive_write_disk *, const char *);
376 static int older(struct stat *, struct archive_entry *);
377 static int restore_entry(struct archive_write_disk *);
378 static int set_mac_metadata(struct archive_write_disk *, const char *,
379 const void *, size_t);
380 static int set_xattrs(struct archive_write_disk *);
381 static int clear_nochange_fflags(struct archive_write_disk *);
382 static int set_fflags(struct archive_write_disk *);
383 static int set_fflags_platform(struct archive_write_disk *, int fd,
384 const char *name, mode_t mode,
385 unsigned long fflags_set, unsigned long fflags_clear);
386 static int set_ownership(struct archive_write_disk *);
387 static int set_mode(struct archive_write_disk *, int mode);
388 static int set_time(int, int, const char *, time_t, long, time_t, long);
389 static int set_times(struct archive_write_disk *, int, int, const char *,
390 time_t, long, time_t, long, time_t, long, time_t, long);
391 static int set_times_from_entry(struct archive_write_disk *);
392 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
393 static ssize_t write_data_block(struct archive_write_disk *,
394 const char *, size_t);
396 static struct archive_vtable *archive_write_disk_vtable(void);
398 static int _archive_write_disk_close(struct archive *);
399 static int _archive_write_disk_free(struct archive *);
400 static int _archive_write_disk_header(struct archive *,
401 struct archive_entry *);
402 static int64_t _archive_write_disk_filter_bytes(struct archive *, int);
403 static int _archive_write_disk_finish_entry(struct archive *);
404 static ssize_t _archive_write_disk_data(struct archive *, const void *,
406 static ssize_t _archive_write_disk_data_block(struct archive *, const void *,
410 la_opendirat(int fd, const char *path) {
411 const int flags = O_CLOEXEC
412 #if defined(O_BINARY)
415 #if defined(O_DIRECTORY)
420 #elif defined(O_SEARCH)
422 #elif defined(O_EXEC)
429 #if !defined(HAVE_OPENAT)
430 if (fd != AT_FDCWD) {
434 return (open(fd, path, flags));
436 return (openat(fd, path, flags));
441 lazy_stat(struct archive_write_disk *a)
443 if (a->pst != NULL) {
444 /* Already have stat() data available. */
448 if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
454 * XXX At this point, symlinks should not be hit, otherwise
455 * XXX a race occurred. Do we want to check explicitly for that?
457 if (lstat(a->name, &a->st) == 0) {
461 archive_set_error(&a->archive, errno, "Couldn't stat file");
462 return (ARCHIVE_WARN);
465 static struct archive_vtable *
466 archive_write_disk_vtable(void)
468 static struct archive_vtable av;
469 static int inited = 0;
472 av.archive_close = _archive_write_disk_close;
473 av.archive_filter_bytes = _archive_write_disk_filter_bytes;
474 av.archive_free = _archive_write_disk_free;
475 av.archive_write_header = _archive_write_disk_header;
476 av.archive_write_finish_entry
477 = _archive_write_disk_finish_entry;
478 av.archive_write_data = _archive_write_disk_data;
479 av.archive_write_data_block = _archive_write_disk_data_block;
486 _archive_write_disk_filter_bytes(struct archive *_a, int n)
488 struct archive_write_disk *a = (struct archive_write_disk *)_a;
489 (void)n; /* UNUSED */
490 if (n == -1 || n == 0)
491 return (a->total_bytes_written);
497 archive_write_disk_set_options(struct archive *_a, int flags)
499 struct archive_write_disk *a = (struct archive_write_disk *)_a;
507 * Extract this entry to disk.
509 * TODO: Validate hardlinks. According to the standards, we're
510 * supposed to check each extracted hardlink and squawk if it refers
511 * to a file that we didn't restore. I'm not entirely convinced this
512 * is a good idea, but more importantly: Is there any way to validate
513 * hardlinks without keeping a complete list of filenames from the
514 * entire archive?? Ugh.
518 _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
520 struct archive_write_disk *a = (struct archive_write_disk *)_a;
521 struct fixup_entry *fe;
524 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
525 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
526 "archive_write_disk_header");
527 archive_clear_error(&a->archive);
528 if (a->archive.state & ARCHIVE_STATE_DATA) {
529 r = _archive_write_disk_finish_entry(&a->archive);
530 if (r == ARCHIVE_FATAL)
534 /* Set up for this particular entry. */
536 a->current_fixup = NULL;
539 archive_entry_free(a->entry);
542 a->entry = archive_entry_clone(entry);
547 a->uid = a->user_uid;
548 a->mode = archive_entry_mode(a->entry);
549 if (archive_entry_size_is_set(a->entry))
550 a->filesize = archive_entry_size(a->entry);
553 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
554 a->name = a->_name_data.s;
555 archive_clear_error(&a->archive);
558 * Clean up the requested path. This is necessary for correct
559 * dir restores; the dir restore logic otherwise gets messed
560 * up by nonsense like "dir/.".
562 ret = cleanup_pathname(a);
563 if (ret != ARCHIVE_OK)
567 * Query the umask so we get predictable mode settings.
568 * This gets done on every call to _write_header in case the
569 * user edits their umask during the extraction for some
572 umask(a->user_umask = umask(0));
574 /* Figure out what we need to do for this entry. */
575 a->todo = TODO_MODE_BASE;
576 if (a->flags & ARCHIVE_EXTRACT_PERM) {
577 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
579 * SGID requires an extra "check" step because we
580 * cannot easily predict the GID that the system will
581 * assign. (Different systems assign GIDs to files
582 * based on a variety of criteria, including process
583 * credentials and the gid of the enclosing
584 * directory.) We can only restore the SGID bit if
585 * the file has the right GID, and we only know the
586 * GID if we either set it (see set_ownership) or if
587 * we've actually called stat() on the file after it
588 * was restored. Since there are several places at
589 * which we might verify the GID, we need a TODO bit
592 if (a->mode & S_ISGID)
593 a->todo |= TODO_SGID | TODO_SGID_CHECK;
595 * Verifying the SUID is simpler, but can still be
596 * done in multiple ways, hence the separate "check" bit.
598 if (a->mode & S_ISUID)
599 a->todo |= TODO_SUID | TODO_SUID_CHECK;
602 * User didn't request full permissions, so don't
603 * restore SUID, SGID bits and obey umask.
608 a->mode &= ~a->user_umask;
610 if (a->flags & ARCHIVE_EXTRACT_OWNER)
611 a->todo |= TODO_OWNER;
612 if (a->flags & ARCHIVE_EXTRACT_TIME)
613 a->todo |= TODO_TIMES;
614 if (a->flags & ARCHIVE_EXTRACT_ACL) {
615 #if ARCHIVE_ACL_DARWIN
617 * On MacOS, platform ACLs get stored in mac_metadata, too.
618 * If we intend to extract mac_metadata and it is present
619 * we skip extracting libarchive NFSv4 ACLs.
621 size_t metadata_size;
623 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
624 archive_entry_mac_metadata(a->entry,
625 &metadata_size) == NULL || metadata_size == 0)
627 #if ARCHIVE_ACL_LIBRICHACL
629 * RichACLs are stored in an extended attribute.
630 * If we intend to extract extended attributes and have this
631 * attribute we skip extracting libarchive NFSv4 ACLs.
633 short extract_acls = 1;
634 if (a->flags & ARCHIVE_EXTRACT_XATTR && (
635 archive_entry_acl_types(a->entry) &
636 ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
637 const char *attr_name;
638 const void *attr_value;
640 int i = archive_entry_xattr_reset(a->entry);
642 archive_entry_xattr_next(a->entry, &attr_name,
643 &attr_value, &attr_size);
644 if (attr_name != NULL && attr_value != NULL &&
645 attr_size > 0 && strcmp(attr_name,
646 "trusted.richacl") == 0) {
654 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
657 if (archive_entry_filetype(a->entry) == AE_IFDIR)
658 a->deferred |= TODO_ACLS;
660 a->todo |= TODO_ACLS;
661 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
665 if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
666 if (archive_entry_filetype(a->entry) == AE_IFDIR)
667 a->deferred |= TODO_MAC_METADATA;
669 a->todo |= TODO_MAC_METADATA;
671 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
672 if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
673 unsigned long set, clear;
674 archive_entry_fflags(a->entry, &set, &clear);
675 if ((set & ~clear) & UF_COMPRESSED) {
676 a->todo |= TODO_HFS_COMPRESSION;
677 a->decmpfs_block_count = (unsigned)-1;
680 if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
681 (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
682 a->todo |= TODO_HFS_COMPRESSION;
683 a->decmpfs_block_count = (unsigned)-1;
688 /* Check if the current file name is a type of the
689 * resource fork file. */
690 p = strrchr(a->name, '/');
695 if (p[0] == '.' && p[1] == '_') {
696 /* Do not compress "._XXX" files. */
697 a->todo &= ~TODO_HFS_COMPRESSION;
699 a->todo |= TODO_APPLEDOUBLE;
704 if (a->flags & ARCHIVE_EXTRACT_XATTR) {
705 #if ARCHIVE_XATTR_DARWIN
707 * On MacOS, extended attributes get stored in mac_metadata,
708 * too. If we intend to extract mac_metadata and it is present
709 * we skip extracting extended attributes.
711 size_t metadata_size;
713 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
714 archive_entry_mac_metadata(a->entry,
715 &metadata_size) == NULL || metadata_size == 0)
717 a->todo |= TODO_XATTR;
719 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
720 a->todo |= TODO_FFLAGS;
721 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
722 ret = check_symlinks(a);
723 if (ret != ARCHIVE_OK)
726 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
727 /* If path exceeds PATH_MAX, shorten the path. */
728 edit_deep_directories(a);
731 ret = restore_entry(a);
733 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
735 * Check if the filesystem the file is restoring on supports
736 * HFS+ Compression. If not, cancel HFS+ Compression.
738 if (a->todo | TODO_HFS_COMPRESSION) {
740 * NOTE: UF_COMPRESSED is ignored even if the filesystem
741 * supports HFS+ Compression because the file should
742 * have at least an extended attribute "com.apple.decmpfs"
743 * before the flag is set to indicate that the file have
744 * been compressed. If the filesystem does not support
745 * HFS+ Compression the system call will fail.
747 if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
748 a->todo &= ~TODO_HFS_COMPRESSION;
753 * TODO: There are rumours that some extended attributes must
754 * be restored before file data is written. If this is true,
755 * then we either need to write all extended attributes both
756 * before and after restoring the data, or find some rule for
757 * determining which must go first and which last. Due to the
758 * many ways people are using xattrs, this may prove to be an
759 * intractable problem.
763 /* If we changed directory above, restore it here. */
764 if (a->restore_pwd >= 0) {
765 r = fchdir(a->restore_pwd);
767 archive_set_error(&a->archive, errno,
771 close(a->restore_pwd);
777 * Fixup uses the unedited pathname from archive_entry_pathname(),
778 * because it is relative to the base dir and the edited path
779 * might be relative to some intermediate dir as a result of the
780 * deep restore logic.
782 if (a->deferred & TODO_MODE) {
783 fe = current_fixup(a, archive_entry_pathname(entry));
785 return (ARCHIVE_FATAL);
786 fe->fixup |= TODO_MODE_BASE;
790 if ((a->deferred & TODO_TIMES)
791 && (archive_entry_mtime_is_set(entry)
792 || archive_entry_atime_is_set(entry))) {
793 fe = current_fixup(a, archive_entry_pathname(entry));
795 return (ARCHIVE_FATAL);
797 fe->fixup |= TODO_TIMES;
798 if (archive_entry_atime_is_set(entry)) {
799 fe->atime = archive_entry_atime(entry);
800 fe->atime_nanos = archive_entry_atime_nsec(entry);
802 /* If atime is unset, use start time. */
803 fe->atime = a->start_time;
806 if (archive_entry_mtime_is_set(entry)) {
807 fe->mtime = archive_entry_mtime(entry);
808 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
810 /* If mtime is unset, use start time. */
811 fe->mtime = a->start_time;
814 if (archive_entry_birthtime_is_set(entry)) {
815 fe->birthtime = archive_entry_birthtime(entry);
816 fe->birthtime_nanos = archive_entry_birthtime_nsec(
819 /* If birthtime is unset, use mtime. */
820 fe->birthtime = fe->mtime;
821 fe->birthtime_nanos = fe->mtime_nanos;
825 if (a->deferred & TODO_ACLS) {
826 fe = current_fixup(a, archive_entry_pathname(entry));
828 return (ARCHIVE_FATAL);
829 fe->fixup |= TODO_ACLS;
830 archive_acl_copy(&fe->acl, archive_entry_acl(entry));
833 if (a->deferred & TODO_MAC_METADATA) {
834 const void *metadata;
835 size_t metadata_size;
836 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
837 if (metadata != NULL && metadata_size > 0) {
838 fe = current_fixup(a, archive_entry_pathname(entry));
840 return (ARCHIVE_FATAL);
841 fe->mac_metadata = malloc(metadata_size);
842 if (fe->mac_metadata != NULL) {
843 memcpy(fe->mac_metadata, metadata,
845 fe->mac_metadata_size = metadata_size;
846 fe->fixup |= TODO_MAC_METADATA;
851 if (a->deferred & TODO_FFLAGS) {
852 fe = current_fixup(a, archive_entry_pathname(entry));
854 return (ARCHIVE_FATAL);
855 fe->fixup |= TODO_FFLAGS;
856 /* TODO: Complete this.. defer fflags from below. */
859 /* We've created the object and are ready to pour data into it. */
860 if (ret >= ARCHIVE_WARN)
861 a->archive.state = ARCHIVE_STATE_DATA;
863 * If it's not open, tell our client not to try writing.
864 * In particular, dirs, links, etc, don't get written to.
867 archive_entry_set_size(entry, 0);
875 archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
877 struct archive_write_disk *a = (struct archive_write_disk *)_a;
878 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
879 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
880 a->skip_file_set = 1;
881 a->skip_file_dev = d;
882 a->skip_file_ino = i;
887 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
889 uint64_t start_size = size;
890 ssize_t bytes_written = 0;
891 ssize_t block_size = 0, bytes_to_write;
896 if (a->filesize == 0 || a->fd < 0) {
897 archive_set_error(&a->archive, 0,
898 "Attempt to write to an empty file");
899 return (ARCHIVE_WARN);
902 if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
903 #if HAVE_STRUCT_STAT_ST_BLKSIZE
905 if ((r = lazy_stat(a)) != ARCHIVE_OK)
907 block_size = a->pst->st_blksize;
909 /* XXX TODO XXX Is there a more appropriate choice here ? */
910 /* This needn't match the filesystem allocation size. */
911 block_size = 16*1024;
915 /* If this write would run beyond the file size, truncate it. */
916 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
917 start_size = size = (size_t)(a->filesize - a->offset);
919 /* Write the data. */
921 if (block_size == 0) {
922 bytes_to_write = size;
924 /* We're sparsifying the file. */
928 /* Skip leading zero bytes. */
929 for (p = buff, end = buff + size; p < end; ++p) {
933 a->offset += p - buff;
939 /* Calculate next block boundary after offset. */
941 = (a->offset / block_size + 1) * block_size;
943 /* If the adjusted write would cross block boundary,
944 * truncate it to the block boundary. */
945 bytes_to_write = size;
946 if (a->offset + bytes_to_write > block_end)
947 bytes_to_write = block_end - a->offset;
949 /* Seek if necessary to the specified offset. */
950 if (a->offset != a->fd_offset) {
951 if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
952 archive_set_error(&a->archive, errno,
954 return (ARCHIVE_FATAL);
956 a->fd_offset = a->offset;
958 bytes_written = write(a->fd, buff, bytes_to_write);
959 if (bytes_written < 0) {
960 archive_set_error(&a->archive, errno, "Write failed");
961 return (ARCHIVE_WARN);
963 buff += bytes_written;
964 size -= bytes_written;
965 a->total_bytes_written += bytes_written;
966 a->offset += bytes_written;
967 a->fd_offset = a->offset;
969 return (start_size - size);
972 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
973 && defined(HAVE_ZLIB_H)
976 * Set UF_COMPRESSED file flag.
977 * This have to be called after hfs_write_decmpfs() because if the
978 * file does not have "com.apple.decmpfs" xattr the flag is ignored.
981 hfs_set_compressed_fflag(struct archive_write_disk *a)
985 if ((r = lazy_stat(a)) != ARCHIVE_OK)
988 a->st.st_flags |= UF_COMPRESSED;
989 if (fchflags(a->fd, a->st.st_flags) != 0) {
990 archive_set_error(&a->archive, errno,
991 "Failed to set UF_COMPRESSED file flag");
992 return (ARCHIVE_WARN);
998 * HFS+ Compression decmpfs
1000 * +------------------------------+ +0
1001 * | Magic(LE 4 bytes) |
1002 * +------------------------------+
1003 * | Type(LE 4 bytes) |
1004 * +------------------------------+
1005 * | Uncompressed size(LE 8 bytes)|
1006 * +------------------------------+ +16
1008 * | Compressed data |
1009 * | (Placed only if Type == 3) |
1011 * +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE
1013 * Type is 3: decmpfs has compressed data.
1014 * Type is 4: Resource Fork has compressed data.
1017 * Write "com.apple.decmpfs"
1020 hfs_write_decmpfs(struct archive_write_disk *a)
1023 uint32_t compression_type;
1025 r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1026 a->decmpfs_attr_size, 0, 0);
1028 archive_set_error(&a->archive, errno,
1029 "Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
1030 compression_type = archive_le32dec(
1031 &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
1032 if (compression_type == CMP_RESOURCE_FORK)
1033 fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
1034 XATTR_SHOWCOMPRESSION);
1035 return (ARCHIVE_WARN);
1037 return (ARCHIVE_OK);
1041 * HFS+ Compression Resource Fork
1043 * +-----------------------------+
1044 * | Header(260 bytes) |
1045 * +-----------------------------+
1046 * | Block count(LE 4 bytes) |
1047 * +-----------------------------+ --+
1048 * +-- | Offset (LE 4 bytes) | |
1049 * | | [distance from Block count] | | Block 0
1050 * | +-----------------------------+ |
1051 * | | Compressed size(LE 4 bytes) | |
1052 * | +-----------------------------+ --+
1054 * | | .................. |
1056 * | +-----------------------------+ --+
1057 * | | Offset (LE 4 bytes) | |
1058 * | +-----------------------------+ | Block (Block count -1)
1059 * | | Compressed size(LE 4 bytes) | |
1060 * +-> +-----------------------------+ --+
1061 * | Compressed data(n bytes) | Block 0
1062 * +-----------------------------+
1064 * | .................. |
1066 * +-----------------------------+
1067 * | Compressed data(n bytes) | Block (Block count -1)
1068 * +-----------------------------+
1069 * | Footer(50 bytes) |
1070 * +-----------------------------+
1074 * Write the header of "com.apple.ResourceFork"
1077 hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1078 size_t bytes, uint32_t position)
1082 ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1083 position, a->rsrc_xattr_options);
1085 archive_set_error(&a->archive, errno,
1086 "Cannot restore xattr: %s at %u pos %u bytes",
1087 XATTR_RESOURCEFORK_NAME,
1090 return (ARCHIVE_WARN);
1092 a->rsrc_xattr_options &= ~XATTR_CREATE;
1093 return (ARCHIVE_OK);
1097 hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1101 ret = hfs_write_resource_fork(a, a->compressed_buffer,
1102 bytes_compressed, a->compressed_rsrc_position);
1103 if (ret == ARCHIVE_OK)
1104 a->compressed_rsrc_position += bytes_compressed;
1109 hfs_write_resource_fork_header(struct archive_write_disk *a)
1111 unsigned char *buff;
1112 uint32_t rsrc_bytes;
1113 uint32_t rsrc_header_bytes;
1116 * Write resource fork header + block info.
1118 buff = a->resource_fork;
1119 rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1121 RSRC_H_SIZE + /* Header base size. */
1122 4 + /* Block count. */
1123 (a->decmpfs_block_count * 8);/* Block info */
1124 archive_be32enc(buff, 0x100);
1125 archive_be32enc(buff + 4, rsrc_bytes);
1126 archive_be32enc(buff + 8, rsrc_bytes - 256);
1127 archive_be32enc(buff + 12, 0x32);
1128 memset(buff + 16, 0, 240);
1129 archive_be32enc(buff + 256, rsrc_bytes - 260);
1130 return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
1134 hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1136 static const char rsrc_footer[RSRC_F_SIZE] = {
1137 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1138 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1139 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1140 0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm',
1141 'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
1142 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1145 if (buff_size < sizeof(rsrc_footer))
1147 memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1148 return (sizeof(rsrc_footer));
1152 hfs_reset_compressor(struct archive_write_disk *a)
1156 if (a->stream_valid)
1157 ret = deflateReset(&a->stream);
1159 ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1162 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1163 "Failed to initialize compressor");
1164 return (ARCHIVE_FATAL);
1166 a->stream_valid = 1;
1168 return (ARCHIVE_OK);
1172 hfs_decompress(struct archive_write_disk *a)
1174 uint32_t *block_info;
1175 unsigned int block_count;
1176 uint32_t data_pos, data_size;
1178 ssize_t bytes_written, bytes_to_write;
1181 block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1182 block_count = archive_le32dec(block_info++);
1183 while (block_count--) {
1184 data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
1185 data_size = archive_le32dec(block_info++);
1186 r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
1187 a->compressed_buffer, data_size, data_pos, 0);
1188 if (r != data_size) {
1189 archive_set_error(&a->archive,
1190 (r < 0)?errno:ARCHIVE_ERRNO_MISC,
1191 "Failed to read resource fork");
1192 return (ARCHIVE_WARN);
1194 if (a->compressed_buffer[0] == 0xff) {
1195 bytes_to_write = data_size -1;
1196 b = a->compressed_buffer + 1;
1198 uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1201 zr = uncompress((Bytef *)a->uncompressed_buffer,
1202 &dest_len, a->compressed_buffer, data_size);
1204 archive_set_error(&a->archive,
1206 "Failed to decompress resource fork");
1207 return (ARCHIVE_WARN);
1209 bytes_to_write = dest_len;
1210 b = (unsigned char *)a->uncompressed_buffer;
1213 bytes_written = write(a->fd, b, bytes_to_write);
1214 if (bytes_written < 0) {
1215 archive_set_error(&a->archive, errno,
1217 return (ARCHIVE_WARN);
1219 bytes_to_write -= bytes_written;
1221 } while (bytes_to_write > 0);
1223 r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1225 archive_set_error(&a->archive, errno,
1226 "Failed to remove resource fork");
1227 return (ARCHIVE_WARN);
1229 return (ARCHIVE_OK);
1233 hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1236 unsigned char *buffer_compressed;
1237 size_t bytes_compressed;
1241 ret = hfs_reset_compressor(a);
1242 if (ret != ARCHIVE_OK)
1245 if (a->compressed_buffer == NULL) {
1248 block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
1249 + compressBound(MAX_DECMPFS_BLOCK_SIZE);
1250 a->compressed_buffer = malloc(block_size);
1251 if (a->compressed_buffer == NULL) {
1252 archive_set_error(&a->archive, ENOMEM,
1253 "Can't allocate memory for Resource Fork");
1254 return (ARCHIVE_FATAL);
1256 a->compressed_buffer_size = block_size;
1257 a->compressed_buffer_remaining = block_size;
1260 buffer_compressed = a->compressed_buffer +
1261 a->compressed_buffer_size - a->compressed_buffer_remaining;
1262 a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
1263 a->stream.avail_in = size;
1264 a->stream.next_out = buffer_compressed;
1265 a->stream.avail_out = a->compressed_buffer_remaining;
1267 ret = deflate(&a->stream, Z_FINISH);
1273 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1274 "Failed to compress data");
1275 return (ARCHIVE_FAILED);
1277 } while (ret == Z_OK);
1278 bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1281 * If the compressed size is larger than the original size,
1282 * throw away compressed data, use uncompressed data instead.
1284 if (bytes_compressed > size) {
1285 buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1286 memcpy(buffer_compressed + 1, buff, size);
1287 bytes_compressed = size + 1;
1289 a->compressed_buffer_remaining -= bytes_compressed;
1292 * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
1293 * and the block count in the file is only one, store compressed
1294 * data to decmpfs xattr instead of the resource fork.
1296 if (a->decmpfs_block_count == 1 &&
1297 (a->decmpfs_attr_size + bytes_compressed)
1298 <= MAX_DECMPFS_XATTR_SIZE) {
1299 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1301 memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
1302 buffer_compressed, bytes_compressed);
1303 a->decmpfs_attr_size += bytes_compressed;
1304 a->compressed_buffer_remaining = a->compressed_buffer_size;
1306 * Finish HFS+ Compression.
1307 * - Write the decmpfs xattr.
1308 * - Set the UF_COMPRESSED file flag.
1310 ret = hfs_write_decmpfs(a);
1311 if (ret == ARCHIVE_OK)
1312 ret = hfs_set_compressed_fflag(a);
1316 /* Update block info. */
1317 archive_le32enc(a->decmpfs_block_info++,
1318 a->compressed_rsrc_position_v - RSRC_H_SIZE);
1319 archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
1320 a->compressed_rsrc_position_v += bytes_compressed;
1323 * Write the compressed data to the resource fork.
1325 bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
1326 while (bytes_used >= COMPRESSED_W_SIZE) {
1327 ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
1328 if (ret != ARCHIVE_OK)
1330 bytes_used -= COMPRESSED_W_SIZE;
1331 if (bytes_used > COMPRESSED_W_SIZE)
1332 memmove(a->compressed_buffer,
1333 a->compressed_buffer + COMPRESSED_W_SIZE,
1336 memcpy(a->compressed_buffer,
1337 a->compressed_buffer + COMPRESSED_W_SIZE,
1340 a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1343 * If the current block is the last block, write the remaining
1344 * compressed data and the resource fork footer.
1346 if (a->file_remaining_bytes == 0) {
1350 /* Append the resource footer. */
1351 rsrc_size = hfs_set_resource_fork_footer(
1352 a->compressed_buffer + bytes_used,
1353 a->compressed_buffer_remaining);
1354 ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
1355 a->compressed_buffer_remaining = a->compressed_buffer_size;
1357 /* If the compressed size is not enough smaller than
1358 * the uncompressed size. cancel HFS+ compression.
1359 * TODO: study a behavior of ditto utility and improve
1360 * the condition to fall back into no HFS+ compression. */
1361 bk = HFS_BLOCKS(a->compressed_rsrc_position);
1363 if (bk > HFS_BLOCKS(a->filesize))
1364 return hfs_decompress(a);
1366 * Write the resourcefork header.
1368 if (ret == ARCHIVE_OK)
1369 ret = hfs_write_resource_fork_header(a);
1371 * Finish HFS+ Compression.
1372 * - Write the decmpfs xattr.
1373 * - Set the UF_COMPRESSED file flag.
1375 if (ret == ARCHIVE_OK)
1376 ret = hfs_write_decmpfs(a);
1377 if (ret == ARCHIVE_OK)
1378 ret = hfs_set_compressed_fflag(a);
1384 hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1387 const char *buffer_to_write;
1388 size_t bytes_to_write;
1391 if (a->decmpfs_block_count == (unsigned)-1) {
1394 unsigned int block_count;
1396 if (a->decmpfs_header_p == NULL) {
1397 new_block = malloc(MAX_DECMPFS_XATTR_SIZE
1398 + sizeof(uint32_t));
1399 if (new_block == NULL) {
1400 archive_set_error(&a->archive, ENOMEM,
1401 "Can't allocate memory for decmpfs");
1402 return (ARCHIVE_FATAL);
1404 a->decmpfs_header_p = new_block;
1406 a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1407 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1409 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1411 archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1414 /* Calculate a block count of the file. */
1416 (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1417 MAX_DECMPFS_BLOCK_SIZE;
1419 * Allocate buffer for resource fork.
1420 * Set up related pointers;
1423 RSRC_H_SIZE + /* header */
1424 4 + /* Block count */
1425 (block_count * sizeof(uint32_t) * 2) +
1426 RSRC_F_SIZE; /* footer */
1427 if (new_size > a->resource_fork_allocated_size) {
1428 new_block = realloc(a->resource_fork, new_size);
1429 if (new_block == NULL) {
1430 archive_set_error(&a->archive, ENOMEM,
1431 "Can't allocate memory for ResourceFork");
1432 return (ARCHIVE_FATAL);
1434 a->resource_fork_allocated_size = new_size;
1435 a->resource_fork = new_block;
1438 /* Allocate uncompressed buffer */
1439 if (a->uncompressed_buffer == NULL) {
1440 new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
1441 if (new_block == NULL) {
1442 archive_set_error(&a->archive, ENOMEM,
1443 "Can't allocate memory for decmpfs");
1444 return (ARCHIVE_FATAL);
1446 a->uncompressed_buffer = new_block;
1448 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1449 a->file_remaining_bytes = a->filesize;
1450 a->compressed_buffer_remaining = a->compressed_buffer_size;
1453 * Set up a resource fork.
1455 a->rsrc_xattr_options = XATTR_CREATE;
1456 /* Get the position where we are going to set a bunch
1458 a->decmpfs_block_info =
1459 (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1460 /* Set the block count to the resource fork. */
1461 archive_le32enc(a->decmpfs_block_info++, block_count);
1462 /* Get the position where we are going to set compressed
1464 a->compressed_rsrc_position =
1465 RSRC_H_SIZE + 4 + (block_count * 8);
1466 a->compressed_rsrc_position_v = a->compressed_rsrc_position;
1467 a->decmpfs_block_count = block_count;
1470 /* Ignore redundant bytes. */
1471 if (a->file_remaining_bytes == 0)
1472 return ((ssize_t)size);
1474 /* Do not overrun a block size. */
1475 if (size > a->block_remaining_bytes)
1476 bytes_to_write = a->block_remaining_bytes;
1478 bytes_to_write = size;
1479 /* Do not overrun the file size. */
1480 if (bytes_to_write > a->file_remaining_bytes)
1481 bytes_to_write = a->file_remaining_bytes;
1483 /* For efficiency, if a copy length is full of the uncompressed
1484 * buffer size, do not copy writing data to it. */
1485 if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
1486 buffer_to_write = buff;
1488 memcpy(a->uncompressed_buffer +
1489 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
1490 buff, bytes_to_write);
1491 buffer_to_write = a->uncompressed_buffer;
1493 a->block_remaining_bytes -= bytes_to_write;
1494 a->file_remaining_bytes -= bytes_to_write;
1496 if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
1497 ret = hfs_drive_compressor(a, buffer_to_write,
1498 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
1501 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1503 /* Ignore redundant bytes. */
1504 if (a->file_remaining_bytes == 0)
1505 return ((ssize_t)size);
1506 return (bytes_to_write);
1510 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1513 uint64_t start_size = size;
1514 ssize_t bytes_written = 0;
1515 ssize_t bytes_to_write;
1518 return (ARCHIVE_OK);
1520 if (a->filesize == 0 || a->fd < 0) {
1521 archive_set_error(&a->archive, 0,
1522 "Attempt to write to an empty file");
1523 return (ARCHIVE_WARN);
1526 /* If this write would run beyond the file size, truncate it. */
1527 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
1528 start_size = size = (size_t)(a->filesize - a->offset);
1530 /* Write the data. */
1532 bytes_to_write = size;
1533 /* Seek if necessary to the specified offset. */
1534 if (a->offset < a->fd_offset) {
1535 /* Can't support backward move. */
1536 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1538 return (ARCHIVE_FATAL);
1539 } else if (a->offset > a->fd_offset) {
1540 int64_t skip = a->offset - a->fd_offset;
1541 char nullblock[1024];
1543 memset(nullblock, 0, sizeof(nullblock));
1545 if (skip > (int64_t)sizeof(nullblock))
1546 bytes_written = hfs_write_decmpfs_block(
1547 a, nullblock, sizeof(nullblock));
1549 bytes_written = hfs_write_decmpfs_block(
1550 a, nullblock, skip);
1551 if (bytes_written < 0) {
1552 archive_set_error(&a->archive, errno,
1554 return (ARCHIVE_WARN);
1556 skip -= bytes_written;
1559 a->fd_offset = a->offset;
1562 hfs_write_decmpfs_block(a, buff, bytes_to_write);
1563 if (bytes_written < 0)
1564 return (bytes_written);
1565 buff += bytes_written;
1566 size -= bytes_written;
1567 a->total_bytes_written += bytes_written;
1568 a->offset += bytes_written;
1569 a->fd_offset = a->offset;
1571 return (start_size - size);
1575 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1578 return (write_data_block(a, buff, size));
1583 _archive_write_disk_data_block(struct archive *_a,
1584 const void *buff, size_t size, int64_t offset)
1586 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1589 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1590 ARCHIVE_STATE_DATA, "archive_write_data_block");
1593 if (a->todo & TODO_HFS_COMPRESSION)
1594 r = hfs_write_data_block(a, buff, size);
1596 r = write_data_block(a, buff, size);
1599 if ((size_t)r < size) {
1600 archive_set_error(&a->archive, 0,
1601 "Too much data: Truncating file at %ju bytes",
1602 (uintmax_t)a->filesize);
1603 return (ARCHIVE_WARN);
1605 #if ARCHIVE_VERSION_NUMBER < 3999000
1606 return (ARCHIVE_OK);
1613 _archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1615 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1617 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1618 ARCHIVE_STATE_DATA, "archive_write_data");
1620 if (a->todo & TODO_HFS_COMPRESSION)
1621 return (hfs_write_data_block(a, buff, size));
1622 return (write_data_block(a, buff, size));
1626 _archive_write_disk_finish_entry(struct archive *_a)
1628 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1629 int ret = ARCHIVE_OK;
1631 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1632 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1633 "archive_write_finish_entry");
1634 if (a->archive.state & ARCHIVE_STATE_HEADER)
1635 return (ARCHIVE_OK);
1636 archive_clear_error(&a->archive);
1638 /* Pad or truncate file to the right size. */
1640 /* There's no file. */
1641 } else if (a->filesize < 0) {
1642 /* File size is unknown, so we can't set the size. */
1643 } else if (a->fd_offset == a->filesize) {
1644 /* Last write ended at exactly the filesize; we're done. */
1645 /* Hopefully, this is the common case. */
1646 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
1647 } else if (a->todo & TODO_HFS_COMPRESSION) {
1651 if (a->file_remaining_bytes)
1652 memset(null_d, 0, sizeof(null_d));
1653 while (a->file_remaining_bytes) {
1654 if (a->file_remaining_bytes > sizeof(null_d))
1655 r = hfs_write_data_block(
1656 a, null_d, sizeof(null_d));
1658 r = hfs_write_data_block(
1659 a, null_d, a->file_remaining_bytes);
1666 if (ftruncate(a->fd, a->filesize) == -1 &&
1668 archive_set_error(&a->archive, errno,
1669 "File size could not be restored");
1670 return (ARCHIVE_FAILED);
1674 * Not all platforms implement the XSI option to
1675 * extend files via ftruncate. Stat() the file again
1676 * to see what happened.
1679 if ((ret = lazy_stat(a)) != ARCHIVE_OK)
1681 /* We can use lseek()/write() to extend the file if
1682 * ftruncate didn't work or isn't available. */
1683 if (a->st.st_size < a->filesize) {
1684 const char nul = '\0';
1685 if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
1686 archive_set_error(&a->archive, errno,
1688 return (ARCHIVE_FATAL);
1690 if (write(a->fd, &nul, 1) < 0) {
1691 archive_set_error(&a->archive, errno,
1692 "Write to restore size failed");
1693 return (ARCHIVE_FATAL);
1699 /* Restore metadata. */
1702 * This is specific to Mac OS X.
1703 * If the current file is an AppleDouble file, it should be
1704 * linked with the data fork file and remove it.
1706 if (a->todo & TODO_APPLEDOUBLE) {
1707 int r2 = fixup_appledouble(a, a->name);
1708 if (r2 == ARCHIVE_EOF) {
1709 /* The current file has been successfully linked
1710 * with the data fork file and removed. So there
1711 * is nothing to do on the current file. */
1712 goto finish_metadata;
1714 if (r2 < ret) ret = r2;
1718 * Look up the "real" UID only if we're going to need it.
1719 * TODO: the TODO_SGID condition can be dropped here, can't it?
1721 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
1722 a->uid = archive_write_disk_uid(&a->archive,
1723 archive_entry_uname(a->entry),
1724 archive_entry_uid(a->entry));
1726 /* Look up the "real" GID only if we're going to need it. */
1727 /* TODO: the TODO_SUID condition can be dropped here, can't it? */
1728 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
1729 a->gid = archive_write_disk_gid(&a->archive,
1730 archive_entry_gname(a->entry),
1731 archive_entry_gid(a->entry));
1735 * Restore ownership before set_mode tries to restore suid/sgid
1736 * bits. If we set the owner, we know what it is and can skip
1737 * a stat() call to examine the ownership of the file on disk.
1739 if (a->todo & TODO_OWNER) {
1740 int r2 = set_ownership(a);
1741 if (r2 < ret) ret = r2;
1745 * set_mode must precede ACLs on systems such as Solaris and
1746 * FreeBSD where setting the mode implicitly clears extended ACLs
1748 if (a->todo & TODO_MODE) {
1749 int r2 = set_mode(a, a->mode);
1750 if (r2 < ret) ret = r2;
1754 * Security-related extended attributes (such as
1755 * security.capability on Linux) have to be restored last,
1756 * since they're implicitly removed by other file changes.
1758 if (a->todo & TODO_XATTR) {
1759 int r2 = set_xattrs(a);
1760 if (r2 < ret) ret = r2;
1764 * Some flags prevent file modification; they must be restored after
1765 * file contents are written.
1767 if (a->todo & TODO_FFLAGS) {
1768 int r2 = set_fflags(a);
1769 if (r2 < ret) ret = r2;
1773 * Time must follow most other metadata;
1774 * otherwise atime will get changed.
1776 if (a->todo & TODO_TIMES) {
1777 int r2 = set_times_from_entry(a);
1778 if (r2 < ret) ret = r2;
1782 * Mac extended metadata includes ACLs.
1784 if (a->todo & TODO_MAC_METADATA) {
1785 const void *metadata;
1786 size_t metadata_size;
1787 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
1788 if (metadata != NULL && metadata_size > 0) {
1789 int r2 = set_mac_metadata(a, archive_entry_pathname(
1790 a->entry), metadata, metadata_size);
1791 if (r2 < ret) ret = r2;
1796 * ACLs must be restored after timestamps because there are
1797 * ACLs that prevent attribute changes (including time).
1799 if (a->todo & TODO_ACLS) {
1801 r2 = archive_write_disk_set_acls(&a->archive, a->fd,
1802 archive_entry_pathname(a->entry),
1803 archive_entry_acl(a->entry),
1804 archive_entry_mode(a->entry));
1805 if (r2 < ret) ret = r2;
1809 /* If there's an fd, we can close it now. */
1814 /* If there's an entry, we can release it now. */
1815 archive_entry_free(a->entry);
1817 a->archive.state = ARCHIVE_STATE_HEADER;
1822 archive_write_disk_set_group_lookup(struct archive *_a,
1824 la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1825 void (*cleanup_gid)(void *private))
1827 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1828 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1829 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
1831 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1832 (a->cleanup_gid)(a->lookup_gid_data);
1834 a->lookup_gid = lookup_gid;
1835 a->cleanup_gid = cleanup_gid;
1836 a->lookup_gid_data = private_data;
1837 return (ARCHIVE_OK);
1841 archive_write_disk_set_user_lookup(struct archive *_a,
1843 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1844 void (*cleanup_uid)(void *private))
1846 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1847 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1848 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
1850 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1851 (a->cleanup_uid)(a->lookup_uid_data);
1853 a->lookup_uid = lookup_uid;
1854 a->cleanup_uid = cleanup_uid;
1855 a->lookup_uid_data = private_data;
1856 return (ARCHIVE_OK);
1860 archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1862 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1863 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1864 ARCHIVE_STATE_ANY, "archive_write_disk_gid");
1866 return (a->lookup_gid)(a->lookup_gid_data, name, id);
1871 archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1873 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1874 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1875 ARCHIVE_STATE_ANY, "archive_write_disk_uid");
1877 return (a->lookup_uid)(a->lookup_uid_data, name, id);
1882 * Create a new archive_write_disk object and initialize it with global state.
1885 archive_write_disk_new(void)
1887 struct archive_write_disk *a;
1889 a = (struct archive_write_disk *)calloc(1, sizeof(*a));
1892 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
1893 /* We're ready to write a header immediately. */
1894 a->archive.state = ARCHIVE_STATE_HEADER;
1895 a->archive.vtable = archive_write_disk_vtable();
1896 a->start_time = time(NULL);
1897 /* Query and restore the umask. */
1898 umask(a->user_umask = umask(0));
1900 a->user_uid = geteuid();
1901 #endif /* HAVE_GETEUID */
1902 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
1907 a->decmpfs_compression_level = 5;
1909 return (&a->archive);
1914 * If pathname is longer than PATH_MAX, chdir to a suitable
1915 * intermediate dir and edit the path down to a shorter suffix. Note
1916 * that this routine never returns an error; if the chdir() attempt
1917 * fails for any reason, we just go ahead with the long pathname. The
1918 * object creation is likely to fail, but any error will get handled
1921 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
1923 edit_deep_directories(struct archive_write_disk *a)
1926 char *tail = a->name;
1928 /* If path is short, avoid the open() below. */
1929 if (strlen(tail) < PATH_MAX)
1932 /* Try to record our starting dir. */
1933 a->restore_pwd = la_opendirat(AT_FDCWD, ".");
1934 __archive_ensure_cloexec_flag(a->restore_pwd);
1935 if (a->restore_pwd < 0)
1938 /* As long as the path is too long... */
1939 while (strlen(tail) >= PATH_MAX) {
1940 /* Locate a dir prefix shorter than PATH_MAX. */
1941 tail += PATH_MAX - 8;
1942 while (tail > a->name && *tail != '/')
1944 /* Exit if we find a too-long path component. */
1945 if (tail <= a->name)
1947 /* Create the intermediate dir and chdir to it. */
1948 *tail = '\0'; /* Terminate dir portion */
1949 ret = create_dir(a, a->name);
1950 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
1951 ret = ARCHIVE_FAILED;
1952 *tail = '/'; /* Restore the / we removed. */
1953 if (ret != ARCHIVE_OK)
1956 /* The chdir() succeeded; we've now shortened the path. */
1964 * The main restore function.
1967 restore_entry(struct archive_write_disk *a)
1969 int ret = ARCHIVE_OK, en;
1971 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
1973 * TODO: Fix this. Apparently, there are platforms
1974 * that still allow root to hose the entire filesystem
1975 * by unlinking a dir. The S_ISDIR() test above
1976 * prevents us from using unlink() here if the new
1977 * object is a dir, but that doesn't mean the old
1978 * object isn't a dir.
1980 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
1981 (void)clear_nochange_fflags(a);
1982 if (unlink(a->name) == 0) {
1983 /* We removed it, reset cached stat. */
1985 } else if (errno == ENOENT) {
1986 /* File didn't exist, that's just as good. */
1987 } else if (rmdir(a->name) == 0) {
1988 /* It was a dir, but now it's gone. */
1991 /* We tried, but couldn't get rid of it. */
1992 archive_set_error(&a->archive, errno,
1993 "Could not unlink");
1994 return(ARCHIVE_FAILED);
1998 /* Try creating it first; if this fails, we'll try to recover. */
1999 en = create_filesystem_object(a);
2001 if ((en == ENOTDIR || en == ENOENT)
2002 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
2003 /* If the parent dir doesn't exist, try creating it. */
2004 create_parent_dir(a, a->name);
2005 /* Now try to create the object again. */
2006 en = create_filesystem_object(a);
2009 if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
2010 archive_set_error(&a->archive, en,
2011 "Hard-link target '%s' does not exist.",
2012 archive_entry_hardlink(a->entry));
2013 return (ARCHIVE_FAILED);
2016 if ((en == EISDIR || en == EEXIST)
2017 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2018 /* If we're not overwriting, we're done. */
2019 if (S_ISDIR(a->mode)) {
2020 /* Don't overwrite any settings on existing directories. */
2023 archive_entry_unset_size(a->entry);
2024 return (ARCHIVE_OK);
2028 * Some platforms return EISDIR if you call
2029 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
2030 * return EEXIST. POSIX is ambiguous, requiring EISDIR
2031 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
2032 * on an existing item.
2035 /* A dir is in the way of a non-dir, rmdir it. */
2036 if (rmdir(a->name) != 0) {
2037 archive_set_error(&a->archive, errno,
2038 "Can't remove already-existing dir");
2039 return (ARCHIVE_FAILED);
2043 en = create_filesystem_object(a);
2044 } else if (en == EEXIST) {
2046 * We know something is in the way, but we don't know what;
2047 * we need to find out before we go any further.
2051 * The SECURE_SYMLINKS logic has already removed a
2052 * symlink to a dir if the client wants that. So
2053 * follow the symlink if we're creating a dir.
2055 if (S_ISDIR(a->mode))
2056 r = la_stat(a->name, &a->st);
2058 * If it's not a dir (or it's a broken symlink),
2059 * then don't follow it.
2061 if (r != 0 || !S_ISDIR(a->mode))
2062 r = lstat(a->name, &a->st);
2064 archive_set_error(&a->archive, errno,
2065 "Can't stat existing object");
2066 return (ARCHIVE_FAILED);
2070 * NO_OVERWRITE_NEWER doesn't apply to directories.
2072 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
2073 && !S_ISDIR(a->st.st_mode)) {
2074 if (!older(&(a->st), a->entry)) {
2075 archive_entry_unset_size(a->entry);
2076 return (ARCHIVE_OK);
2080 /* If it's our archive, we're done. */
2081 if (a->skip_file_set &&
2082 a->st.st_dev == (dev_t)a->skip_file_dev &&
2083 a->st.st_ino == (ino_t)a->skip_file_ino) {
2084 archive_set_error(&a->archive, 0,
2085 "Refusing to overwrite archive");
2086 return (ARCHIVE_FAILED);
2089 if (!S_ISDIR(a->st.st_mode)) {
2090 /* A non-dir is in the way, unlink it. */
2091 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2092 (void)clear_nochange_fflags(a);
2093 if (unlink(a->name) != 0) {
2094 archive_set_error(&a->archive, errno,
2095 "Can't unlink already-existing object");
2096 return (ARCHIVE_FAILED);
2100 en = create_filesystem_object(a);
2101 } else if (!S_ISDIR(a->mode)) {
2102 /* A dir is in the way of a non-dir, rmdir it. */
2103 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2104 (void)clear_nochange_fflags(a);
2105 if (rmdir(a->name) != 0) {
2106 archive_set_error(&a->archive, errno,
2107 "Can't replace existing directory with non-directory");
2108 return (ARCHIVE_FAILED);
2111 en = create_filesystem_object(a);
2114 * There's a dir in the way of a dir. Don't
2115 * waste time with rmdir()/mkdir(), just fix
2116 * up the permissions on the existing dir.
2117 * Note that we don't change perms on existing
2118 * dirs unless _EXTRACT_PERM is specified.
2120 if ((a->mode != a->st.st_mode)
2121 && (a->todo & TODO_MODE_FORCE))
2122 a->deferred |= (a->todo & TODO_MODE);
2123 /* Ownership doesn't need deferred fixup. */
2124 en = 0; /* Forget the EEXIST. */
2129 /* Everything failed; give up here. */
2130 if ((&a->archive)->error == NULL)
2131 archive_set_error(&a->archive, en, "Can't create '%s'",
2133 return (ARCHIVE_FAILED);
2136 a->pst = NULL; /* Cached stat data no longer valid. */
2141 * Returns 0 if creation succeeds, or else returns errno value from
2142 * the failed system call. Note: This function should only ever perform
2143 * a single system call.
2146 create_filesystem_object(struct archive_write_disk *a)
2148 /* Create the entry. */
2149 const char *linkname;
2150 mode_t final_mode, mode;
2152 /* these for check_symlinks_fsobj */
2153 char *linkname_copy; /* non-const copy of linkname */
2155 struct archive_string error_string;
2158 /* We identify hard/symlinks according to the link names. */
2159 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
2160 linkname = archive_entry_hardlink(a->entry);
2161 if (linkname != NULL) {
2165 archive_string_init(&error_string);
2166 linkname_copy = strdup(linkname);
2167 if (linkname_copy == NULL) {
2171 * TODO: consider using the cleaned-up path as the link
2174 r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2175 &error_string, a->flags);
2176 if (r != ARCHIVE_OK) {
2177 archive_set_error(&a->archive, error_number, "%s",
2179 free(linkname_copy);
2180 archive_string_free(&error_string);
2182 * EPERM is more appropriate than error_number for our
2187 r = check_symlinks_fsobj(linkname_copy, &error_number,
2188 &error_string, a->flags);
2189 if (r != ARCHIVE_OK) {
2190 archive_set_error(&a->archive, error_number, "%s",
2192 free(linkname_copy);
2193 archive_string_free(&error_string);
2195 * EPERM is more appropriate than error_number for our
2200 free(linkname_copy);
2201 archive_string_free(&error_string);
2202 r = link(linkname, a->name) ? errno : 0;
2204 * New cpio and pax formats allow hardlink entries
2205 * to carry data, so we may have to open the file
2206 * for hardlink entries.
2208 * If the hardlink was successfully created and
2209 * the archive doesn't have carry data for it,
2210 * consider it to be non-authoritative for meta data.
2211 * This is consistent with GNU tar and BSD pax.
2212 * If the hardlink does carry data, let the last
2213 * archive entry decide ownership.
2215 if (r == 0 && a->filesize <= 0) {
2218 } else if (r == 0 && a->filesize > 0) {
2220 r = lstat(a->name, &st);
2222 r = la_stat(a->name, &st);
2226 else if ((st.st_mode & AE_IFMT) == AE_IFREG) {
2227 a->fd = open(a->name, O_WRONLY | O_TRUNC |
2228 O_BINARY | O_CLOEXEC | O_NOFOLLOW);
2229 __archive_ensure_cloexec_flag(a->fd);
2237 linkname = archive_entry_symlink(a->entry);
2238 if (linkname != NULL) {
2240 return symlink(linkname, a->name) ? errno : 0;
2247 * The remaining system calls all set permissions, so let's
2248 * try to take advantage of that to avoid an extra chmod()
2249 * call. (Recall that umask is set to zero right now!)
2252 /* Mode we want for the final restored object (w/o file type bits). */
2253 final_mode = a->mode & 07777;
2255 * The mode that will actually be restored in this step. Note
2256 * that SUID, SGID, etc, require additional work to ensure
2257 * security, so we never restore them at this point.
2259 mode = final_mode & 0777 & ~a->user_umask;
2261 switch (a->mode & AE_IFMT) {
2263 /* POSIX requires that we fall through here. */
2266 a->fd = open(a->name,
2267 O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2268 __archive_ensure_cloexec_flag(a->fd);
2273 /* Note: we use AE_IFCHR for the case label, and
2274 * S_IFCHR for the mknod() call. This is correct. */
2275 r = mknod(a->name, mode | S_IFCHR,
2276 archive_entry_rdev(a->entry));
2279 /* TODO: Find a better way to warn about our inability
2280 * to restore a char device node. */
2282 #endif /* HAVE_MKNOD */
2285 r = mknod(a->name, mode | S_IFBLK,
2286 archive_entry_rdev(a->entry));
2289 /* TODO: Find a better way to warn about our inability
2290 * to restore a block device node. */
2292 #endif /* HAVE_MKNOD */
2294 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2295 r = mkdir(a->name, mode);
2297 /* Defer setting dir times. */
2298 a->deferred |= (a->todo & TODO_TIMES);
2299 a->todo &= ~TODO_TIMES;
2300 /* Never use an immediate chmod(). */
2301 /* We can't avoid the chmod() entirely if EXTRACT_PERM
2302 * because of SysV SGID inheritance. */
2303 if ((mode != final_mode)
2304 || (a->flags & ARCHIVE_EXTRACT_PERM))
2305 a->deferred |= (a->todo & TODO_MODE);
2306 a->todo &= ~TODO_MODE;
2311 r = mkfifo(a->name, mode);
2314 /* TODO: Find a better way to warn about our inability
2315 * to restore a fifo. */
2317 #endif /* HAVE_MKFIFO */
2320 /* All the system calls above set errno on failure. */
2324 /* If we managed to set the final mode, we've avoided a chmod(). */
2325 if (mode == final_mode)
2326 a->todo &= ~TODO_MODE;
2331 * Cleanup function for archive_extract. Mostly, this involves processing
2332 * the fixup list, which is used to address a number of problems:
2333 * * Dir permissions might prevent us from restoring a file in that
2334 * dir, so we restore the dir with minimum 0700 permissions first,
2335 * then correct the mode at the end.
2336 * * Similarly, the act of restoring a file touches the directory
2337 * and changes the timestamp on the dir, so we have to touch-up dir
2338 * timestamps at the end as well.
2339 * * Some file flags can interfere with the restore by, for example,
2340 * preventing the creation of hardlinks to those files.
2341 * * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2343 * Note that tar/cpio do not require that archives be in a particular
2344 * order; there is no way to know when the last file has been restored
2345 * within a directory, so there's no way to optimize the memory usage
2346 * here by fixing up the directory any earlier than the
2349 * XXX TODO: Directory ACLs should be restored here, for the same
2350 * reason we set directory perms here. XXX
2353 _archive_write_disk_close(struct archive *_a)
2355 struct archive_write_disk *a = (struct archive_write_disk *)_a;
2356 struct fixup_entry *next, *p;
2359 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2360 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2361 "archive_write_disk_close");
2362 ret = _archive_write_disk_finish_entry(&a->archive);
2364 /* Sort dir list so directories are fixed up in depth-first order. */
2365 p = sort_dir_list(a->fixup_list);
2369 a->pst = NULL; /* Mark stat cache as out-of-date. */
2371 (TODO_TIMES | TODO_MODE_BASE | TODO_ACLS | TODO_FFLAGS)) {
2373 O_WRONLY | O_BINARY | O_NOFOLLOW | O_CLOEXEC);
2375 if (p->fixup & TODO_TIMES) {
2376 set_times(a, fd, p->mode, p->name,
2377 p->atime, p->atime_nanos,
2378 p->birthtime, p->birthtime_nanos,
2379 p->mtime, p->mtime_nanos,
2380 p->ctime, p->ctime_nanos);
2382 if (p->fixup & TODO_MODE_BASE) {
2385 fchmod(fd, p->mode);
2388 chmod(p->name, p->mode);
2390 if (p->fixup & TODO_ACLS)
2391 archive_write_disk_set_acls(&a->archive, fd,
2392 p->name, &p->acl, p->mode);
2393 if (p->fixup & TODO_FFLAGS)
2394 set_fflags_platform(a, fd, p->name,
2395 p->mode, p->fflags_set, 0);
2396 if (p->fixup & TODO_MAC_METADATA)
2397 set_mac_metadata(a, p->name, p->mac_metadata,
2398 p->mac_metadata_size);
2400 archive_acl_clear(&p->acl);
2401 free(p->mac_metadata);
2408 a->fixup_list = NULL;
2413 _archive_write_disk_free(struct archive *_a)
2415 struct archive_write_disk *a;
2418 return (ARCHIVE_OK);
2419 archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2420 ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2421 a = (struct archive_write_disk *)_a;
2422 ret = _archive_write_disk_close(&a->archive);
2423 archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2424 archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2425 archive_entry_free(a->entry);
2426 archive_string_free(&a->_name_data);
2427 archive_string_free(&a->archive.error_string);
2428 archive_string_free(&a->path_safe);
2429 a->archive.magic = 0;
2430 __archive_clean(&a->archive);
2431 free(a->decmpfs_header_p);
2432 free(a->resource_fork);
2433 free(a->compressed_buffer);
2434 free(a->uncompressed_buffer);
2435 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2436 && defined(HAVE_ZLIB_H)
2437 if (a->stream_valid) {
2438 switch (deflateEnd(&a->stream)) {
2442 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2443 "Failed to clean up compressor");
2444 ret = ARCHIVE_FATAL;
2454 * Simple O(n log n) merge sort to order the fixup list. In
2455 * particular, we want to restore dir timestamps depth-first.
2457 static struct fixup_entry *
2458 sort_dir_list(struct fixup_entry *p)
2460 struct fixup_entry *a, *b, *t;
2464 /* A one-item list is already sorted. */
2465 if (p->next == NULL)
2468 /* Step 1: split the list. */
2472 /* Step a twice, t once. */
2478 /* Now, t is at the mid-point, so break the list here. */
2483 /* Step 2: Recursively sort the two sub-lists. */
2484 a = sort_dir_list(a);
2485 b = sort_dir_list(b);
2487 /* Step 3: Merge the returned lists. */
2488 /* Pick the first element for the merged list. */
2489 if (strcmp(a->name, b->name) > 0) {
2497 /* Always put the later element on the list first. */
2498 while (a != NULL && b != NULL) {
2499 if (strcmp(a->name, b->name) > 0) {
2509 /* Only one list is non-empty, so just splice it on. */
2519 * Returns a new, initialized fixup entry.
2521 * TODO: Reduce the memory requirements for this list by using a tree
2522 * structure rather than a simple list of names.
2524 static struct fixup_entry *
2525 new_fixup(struct archive_write_disk *a, const char *pathname)
2527 struct fixup_entry *fe;
2529 fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2531 archive_set_error(&a->archive, ENOMEM,
2532 "Can't allocate memory for a fixup");
2535 fe->next = a->fixup_list;
2538 fe->name = strdup(pathname);
2543 * Returns a fixup structure for the current entry.
2545 static struct fixup_entry *
2546 current_fixup(struct archive_write_disk *a, const char *pathname)
2548 if (a->current_fixup == NULL)
2549 a->current_fixup = new_fixup(a, pathname);
2550 return (a->current_fixup);
2553 /* Error helper for new *_fsobj functions */
2555 fsobj_error(int *a_eno, struct archive_string *a_estr,
2556 int err, const char *errstr, const char *path)
2561 archive_string_sprintf(a_estr, "%s%s", errstr, path);
2565 * TODO: Someday, integrate this with the deep dir support; they both
2566 * scan the path and both can be optimized by comparing against other
2570 * Checks the given path to see if any elements along it are symlinks. Returns
2571 * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2574 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2577 #if !defined(HAVE_LSTAT) && \
2578 !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT))
2579 /* Platform doesn't have lstat, so we can't look for symlinks. */
2580 (void)path; /* UNUSED */
2581 (void)error_number; /* UNUSED */
2582 (void)error_string; /* UNUSED */
2583 (void)flags; /* UNUSED */
2584 return (ARCHIVE_OK);
2586 int res = ARCHIVE_OK;
2594 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2598 /* Nothing to do here if name is empty */
2600 return (ARCHIVE_OK);
2603 * Guard against symlink tricks. Reject any archive entry whose
2604 * destination would be altered by a symlink.
2606 * Walk the filename in chunks separated by '/'. For each segment:
2607 * - if it doesn't exist, continue
2608 * - if it's symlink, abort or remove it
2609 * - if it's a directory and it's not the last chunk, cd into it
2611 * head points to the current (relative) path
2612 * tail points to the temporary \0 terminating the segment we're
2613 * currently examining
2614 * c holds what used to be in *tail
2615 * last is 1 if this is the last tail
2617 chdir_fd = la_opendirat(AT_FDCWD, ".");
2618 __archive_ensure_cloexec_flag(chdir_fd);
2620 fsobj_error(a_eno, a_estr, errno,
2621 "Could not open ", path);
2622 return (ARCHIVE_FATAL);
2627 /* TODO: reintroduce a safe cache here? */
2628 /* Skip the root directory if the path is absolute. */
2629 if(tail == path && tail[0] == '/')
2631 /* Keep going until we've checked the entire name.
2632 * head, tail, path all alias the same string, which is
2633 * temporarily zeroed at tail, so be careful restoring the
2634 * stashed (c=tail[0]) for error messages.
2635 * Exiting the loop with break is okay; continue is not.
2639 * Skip the separator we just consumed, plus any adjacent ones
2641 while (*tail == '/')
2643 /* Skip the next path element. */
2644 while (*tail != '\0' && *tail != '/')
2646 /* is this the last path component? */
2647 last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2648 /* temporarily truncate the string here */
2651 /* Check that we haven't hit a symlink. */
2652 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2653 r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW);
2655 r = lstat(head, &st);
2659 /* We've hit a dir that doesn't exist; stop now. */
2660 if (errno == ENOENT) {
2664 * Treat any other error as fatal - best to be
2666 * Note: This effectively disables deep
2667 * directory support when security checks are
2668 * enabled. Otherwise, very long pathnames that
2669 * trigger an error here could evade the
2671 * TODO: We could do better, but it would
2672 * probably require merging the symlink checks
2673 * with the deep-directory editing.
2675 fsobj_error(a_eno, a_estr, errno,
2676 "Could not stat ", path);
2677 res = ARCHIVE_FAILED;
2680 } else if (S_ISDIR(st.st_mode)) {
2682 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2683 fd = la_opendirat(chdir_fd, head);
2696 fsobj_error(a_eno, a_estr, errno,
2697 "Could not chdir ", path);
2698 res = (ARCHIVE_FATAL);
2701 /* Our view is now from inside this dir: */
2704 } else if (S_ISLNK(st.st_mode)) {
2707 * Last element is symlink; remove it
2708 * so we can overwrite it with the
2709 * item being extracted.
2711 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2712 r = unlinkat(chdir_fd, head, 0);
2718 fsobj_error(a_eno, a_estr, errno,
2719 "Could not remove symlink ",
2721 res = ARCHIVE_FAILED;
2725 * Even if we did remove it, a warning
2726 * is in order. The warning is silly,
2727 * though, if we're just replacing one
2728 * symlink with another symlink.
2732 * FIXME: not sure how important this is to
2736 if (!S_ISLNK(path)) {
2737 fsobj_error(a_eno, a_estr, 0,
2738 "Removing symlink ", path);
2741 /* Symlink gone. No more problem! */
2744 } else if (flags & ARCHIVE_EXTRACT_UNLINK) {
2745 /* User asked us to remove problems. */
2746 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2747 r = unlinkat(chdir_fd, head, 0);
2753 fsobj_error(a_eno, a_estr, 0,
2754 "Cannot remove intervening "
2756 res = ARCHIVE_FAILED;
2761 ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
2763 * We are not the last element and we want to
2764 * follow symlinks if they are a directory.
2766 * This is needed to extract hardlinks over
2769 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2770 r = fstatat(chdir_fd, head, &st, 0);
2772 r = la_stat(head, &st);
2776 if (errno == ENOENT) {
2779 fsobj_error(a_eno, a_estr,
2781 "Could not stat ", path);
2782 res = (ARCHIVE_FAILED);
2785 } else if (S_ISDIR(st.st_mode)) {
2786 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2787 fd = la_opendirat(chdir_fd, head);
2800 fsobj_error(a_eno, a_estr,
2802 "Could not chdir ", path);
2803 res = (ARCHIVE_FATAL);
2807 * Our view is now from inside
2813 fsobj_error(a_eno, a_estr, 0,
2814 "Cannot extract through "
2816 res = ARCHIVE_FAILED;
2821 fsobj_error(a_eno, a_estr, 0,
2822 "Cannot extract through symlink ", path);
2823 res = ARCHIVE_FAILED;
2827 /* be sure to always maintain this */
2829 if (tail[0] != '\0')
2830 tail++; /* Advance to the next segment. */
2832 /* Catches loop exits via break */
2834 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2835 /* If we operate with openat(), fstatat() and unlinkat() there was
2836 * no chdir(), so just close the fd */
2840 /* If we changed directory above, restore it here. */
2841 if (chdir_fd >= 0) {
2842 r = fchdir(chdir_fd);
2844 fsobj_error(a_eno, a_estr, errno,
2845 "chdir() failure", "");
2850 res = (ARCHIVE_FATAL);
2854 /* TODO: reintroduce a safe cache here? */
2860 * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
2861 * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
2864 check_symlinks(struct archive_write_disk *a)
2866 struct archive_string error_string;
2869 archive_string_init(&error_string);
2870 rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
2872 if (rc != ARCHIVE_OK) {
2873 archive_set_error(&a->archive, error_number, "%s",
2876 archive_string_free(&error_string);
2877 a->pst = NULL; /* to be safe */
2882 #if defined(__CYGWIN__)
2884 * 1. Convert a path separator from '\' to '/' .
2885 * We shouldn't check multibyte character directly because some
2886 * character-set have been using the '\' character for a part of
2887 * its multibyte character code.
2888 * 2. Replace unusable characters in Windows with underscore('_').
2889 * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
2892 cleanup_pathname_win(char *path)
2897 int mb, complete, utf8;
2902 utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
2903 for (p = path; *p != '\0'; p++) {
2906 /* If previous byte is smaller than 128,
2907 * this is not second byte of multibyte characters,
2908 * so we can replace '\' with '/'. */
2912 complete = 0;/* uncompleted. */
2913 } else if (*(unsigned char *)p > 127)
2917 /* Rewrite the path name if its next character is unusable. */
2918 if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
2919 *p == '<' || *p == '>' || *p == '|')
2926 * Convert path separator in wide-character.
2929 while (*p != '\0' && alen) {
2930 l = mbtowc(&wc, p, alen);
2931 if (l == (size_t)-1) {
2932 while (*p != '\0') {
2939 if (l == 1 && wc == L'\\')
2948 * Canonicalize the pathname. In particular, this strips duplicate
2949 * '/' characters, '.' elements, and trailing '/'. It also raises an
2950 * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
2951 * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
2952 * is set) if the path is absolute.
2955 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2959 char separator = '\0';
2963 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
2964 "Invalid empty ", "pathname");
2965 return (ARCHIVE_FAILED);
2968 #if defined(__CYGWIN__)
2969 cleanup_pathname_win(path);
2971 /* Skip leading '/'. */
2973 if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
2974 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
2975 "Path is ", "absolute");
2976 return (ARCHIVE_FAILED);
2982 /* Scan the pathname one element at a time. */
2984 /* src points to first char after '/' */
2985 if (src[0] == '\0') {
2987 } else if (src[0] == '/') {
2988 /* Found '//', ignore second one. */
2991 } else if (src[0] == '.') {
2992 if (src[1] == '\0') {
2993 /* Ignore trailing '.' */
2995 } else if (src[1] == '/') {
2999 } else if (src[1] == '.') {
3000 if (src[2] == '/' || src[2] == '\0') {
3001 /* Conditionally warn about '..' */
3003 & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3004 fsobj_error(a_eno, a_estr,
3006 "Path contains ", "'..'");
3007 return (ARCHIVE_FAILED);
3011 * Note: Under no circumstances do we
3012 * remove '..' elements. In
3013 * particular, restoring
3014 * '/foo/../bar/' should create the
3015 * 'foo' dir as a side-effect.
3020 /* Copy current element, including leading '/'. */
3023 while (*src != '\0' && *src != '/') {
3030 /* Skip '/' separator. */
3034 * We've just copied zero or more path elements, not including the
3039 * Nothing got copied. The path must have been something
3040 * like '.' or '/' or './' or '/././././/./'.
3047 /* Terminate the result. */
3049 return (ARCHIVE_OK);
3053 cleanup_pathname(struct archive_write_disk *a)
3055 struct archive_string error_string;
3058 archive_string_init(&error_string);
3059 rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3061 if (rc != ARCHIVE_OK) {
3062 archive_set_error(&a->archive, error_number, "%s",
3065 archive_string_free(&error_string);
3070 * Create the parent directory of the specified path, assuming path
3071 * is already in mutable storage.
3074 create_parent_dir(struct archive_write_disk *a, char *path)
3079 /* Remove tail element to obtain parent name. */
3080 slash = strrchr(path, '/');
3082 return (ARCHIVE_OK);
3084 r = create_dir(a, path);
3090 * Create the specified dir, recursing to create parents as necessary.
3092 * Returns ARCHIVE_OK if the path exists when we're done here.
3093 * Otherwise, returns ARCHIVE_FAILED.
3094 * Assumes path is in mutable storage; path is unchanged on exit.
3097 create_dir(struct archive_write_disk *a, char *path)
3100 struct fixup_entry *le;
3102 mode_t mode_final, mode;
3105 /* Check for special names and just skip them. */
3106 slash = strrchr(path, '/');
3112 if (base[0] == '\0' ||
3113 (base[0] == '.' && base[1] == '\0') ||
3114 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
3115 /* Don't bother trying to create null path, '.', or '..'. */
3116 if (slash != NULL) {
3118 r = create_dir(a, path);
3122 return (ARCHIVE_OK);
3126 * Yes, this should be stat() and not lstat(). Using lstat()
3127 * here loses the ability to extract through symlinks. Also note
3128 * that this should not use the a->st cache.
3130 if (la_stat(path, &st) == 0) {
3131 if (S_ISDIR(st.st_mode))
3132 return (ARCHIVE_OK);
3133 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
3134 archive_set_error(&a->archive, EEXIST,
3135 "Can't create directory '%s'", path);
3136 return (ARCHIVE_FAILED);
3138 if (unlink(path) != 0) {
3139 archive_set_error(&a->archive, errno,
3140 "Can't create directory '%s': "
3141 "Conflicting file cannot be removed",
3143 return (ARCHIVE_FAILED);
3145 } else if (errno != ENOENT && errno != ENOTDIR) {
3147 archive_set_error(&a->archive, errno,
3148 "Can't test directory '%s'", path);
3149 return (ARCHIVE_FAILED);
3150 } else if (slash != NULL) {
3152 r = create_dir(a, path);
3154 if (r != ARCHIVE_OK)
3159 * Mode we want for the final restored directory. Per POSIX,
3160 * implicitly-created dirs must be created obeying the umask.
3161 * There's no mention whether this is different for privileged
3162 * restores (which the rest of this code handles by pretending
3163 * umask=0). I've chosen here to always obey the user's umask for
3164 * implicit dirs, even if _EXTRACT_PERM was specified.
3166 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3167 /* Mode we want on disk during the restore process. */
3169 mode |= MINIMUM_DIR_MODE;
3170 mode &= MAXIMUM_DIR_MODE;
3171 if (mkdir(path, mode) == 0) {
3172 if (mode != mode_final) {
3173 le = new_fixup(a, path);
3175 return (ARCHIVE_FATAL);
3176 le->fixup |=TODO_MODE_BASE;
3177 le->mode = mode_final;
3179 return (ARCHIVE_OK);
3183 * Without the following check, a/b/../b/c/d fails at the
3184 * second visit to 'b', so 'd' can't be created. Note that we
3185 * don't add it to the fixup list here, as it's already been
3188 if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3189 return (ARCHIVE_OK);
3191 archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3193 return (ARCHIVE_FAILED);
3197 * Note: Although we can skip setting the user id if the desired user
3198 * id matches the current user, we cannot skip setting the group, as
3199 * many systems set the gid based on the containing directory. So
3200 * we have to perform a chown syscall if we want to set the SGID
3201 * bit. (The alternative is to stat() and then possibly chown(); it's
3202 * more efficient to skip the stat() and just always chown().) Note
3203 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3204 * allows set_mode to skip the stat() check for the GID.
3207 set_ownership(struct archive_write_disk *a)
3209 #if !defined(__CYGWIN__) && !defined(__linux__)
3211 * On Linux, a process may have the CAP_CHOWN capability.
3212 * On Windows there is no 'root' user with uid 0.
3213 * Elsewhere we can skip calling chown if we are not root and the desired
3214 * user id does not match the current user.
3216 if (a->user_uid != 0 && a->user_uid != a->uid) {
3217 archive_set_error(&a->archive, errno,
3218 "Can't set UID=%jd", (intmax_t)a->uid);
3219 return (ARCHIVE_WARN);
3224 /* If we have an fd, we can avoid a race. */
3225 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3226 /* We've set owner and know uid/gid are correct. */
3227 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3228 return (ARCHIVE_OK);
3232 /* We prefer lchown() but will use chown() if that's all we have. */
3233 /* Of course, if we have neither, this will always fail. */
3235 if (lchown(a->name, a->uid, a->gid) == 0) {
3236 /* We've set owner and know uid/gid are correct. */
3237 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3238 return (ARCHIVE_OK);
3241 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3242 /* We've set owner and know uid/gid are correct. */
3243 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3244 return (ARCHIVE_OK);
3248 archive_set_error(&a->archive, errno,
3249 "Can't set user=%jd/group=%jd for %s",
3250 (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3251 return (ARCHIVE_WARN);
3255 * Note: Returns 0 on success, non-zero on failure.
3258 set_time(int fd, int mode, const char *name,
3259 time_t atime, long atime_nsec,
3260 time_t mtime, long mtime_nsec)
3262 /* Select the best implementation for this platform. */
3263 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3265 * utimensat() and futimens() are defined in
3266 * POSIX.1-2008. They support ns resolution and setting times
3267 * on fds and symlinks.
3269 struct timespec ts[2];
3270 (void)mode; /* UNUSED */
3271 ts[0].tv_sec = atime;
3272 ts[0].tv_nsec = atime_nsec;
3273 ts[1].tv_sec = mtime;
3274 ts[1].tv_nsec = mtime_nsec;
3276 return futimens(fd, ts);
3277 return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3281 * The utimes()-family functions support µs-resolution and
3282 * setting times fds and symlinks. utimes() is documented as
3283 * LEGACY by POSIX, futimes() and lutimes() are not described
3286 struct timeval times[2];
3288 times[0].tv_sec = atime;
3289 times[0].tv_usec = atime_nsec / 1000;
3290 times[1].tv_sec = mtime;
3291 times[1].tv_usec = mtime_nsec / 1000;
3295 return (futimes(fd, times));
3297 (void)fd; /* UNUSED */
3300 (void)mode; /* UNUSED */
3301 return (lutimes(name, times));
3305 return (utimes(name, times));
3308 #elif defined(HAVE_UTIME)
3310 * utime() is POSIX-standard but only supports 1s resolution and
3311 * does not support fds or symlinks.
3313 struct utimbuf times;
3314 (void)fd; /* UNUSED */
3315 (void)name; /* UNUSED */
3316 (void)atime_nsec; /* UNUSED */
3317 (void)mtime_nsec; /* UNUSED */
3318 times.actime = atime;
3319 times.modtime = mtime;
3321 return (ARCHIVE_OK);
3322 return (utime(name, ×));
3326 * We don't know how to set the time on this platform.
3328 (void)fd; /* UNUSED */
3329 (void)mode; /* UNUSED */
3330 (void)name; /* UNUSED */
3331 (void)atime_nsec; /* UNUSED */
3332 (void)mtime_nsec; /* UNUSED */
3333 return (ARCHIVE_WARN);
3339 set_time_tru64(int fd, int mode, const char *name,
3340 time_t atime, long atime_nsec,
3341 time_t mtime, long mtime_nsec,
3342 time_t ctime, long ctime_nsec)
3344 struct attr_timbuf tstamp;
3345 tstamp.atime.tv_sec = atime;
3346 tstamp.mtime.tv_sec = mtime;
3347 tstamp.ctime.tv_sec = ctime;
3348 #if defined (__hpux) && defined (__ia64)
3349 tstamp.atime.tv_nsec = atime_nsec;
3350 tstamp.mtime.tv_nsec = mtime_nsec;
3351 tstamp.ctime.tv_nsec = ctime_nsec;
3353 tstamp.atime.tv_usec = atime_nsec / 1000;
3354 tstamp.mtime.tv_usec = mtime_nsec / 1000;
3355 tstamp.ctime.tv_usec = ctime_nsec / 1000;
3357 return (fcntl(fd,F_SETTIMES,&tstamp));
3359 #endif /* F_SETTIMES */
3362 set_times(struct archive_write_disk *a,
3363 int fd, int mode, const char *name,
3364 time_t atime, long atime_nanos,
3365 time_t birthtime, long birthtime_nanos,
3366 time_t mtime, long mtime_nanos,
3367 time_t cctime, long ctime_nanos)
3369 /* Note: set_time doesn't use libarchive return conventions!
3370 * It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */
3375 * on Tru64 try own fcntl first which can restore even the
3376 * ctime, fall back to default code path below if it fails
3377 * or if we are not running as root
3379 if (a->user_uid == 0 &&
3380 set_time_tru64(fd, mode, name,
3381 atime, atime_nanos, mtime,
3382 mtime_nanos, cctime, ctime_nanos) == 0) {
3383 return (ARCHIVE_OK);
3386 (void)cctime; /* UNUSED */
3387 (void)ctime_nanos; /* UNUSED */
3390 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3392 * If you have struct stat.st_birthtime, we assume BSD
3393 * birthtime semantics, in which {f,l,}utimes() updates
3394 * birthtime to earliest mtime. So we set the time twice,
3395 * first using the birthtime, then using the mtime. If
3396 * birthtime == mtime, this isn't necessary, so we skip it.
3397 * If birthtime > mtime, then this won't work, so we skip it.
3399 if (birthtime < mtime
3400 || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3401 r1 = set_time(fd, mode, name,
3403 birthtime, birthtime_nanos);
3405 (void)birthtime; /* UNUSED */
3406 (void)birthtime_nanos; /* UNUSED */
3408 r2 = set_time(fd, mode, name,
3410 mtime, mtime_nanos);
3411 if (r1 != 0 || r2 != 0) {
3412 archive_set_error(&a->archive, errno,
3413 "Can't restore time");
3414 return (ARCHIVE_WARN);
3416 return (ARCHIVE_OK);
3420 set_times_from_entry(struct archive_write_disk *a)
3422 time_t atime, birthtime, mtime, cctime;
3423 long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3425 /* Suitable defaults. */
3426 atime = birthtime = mtime = cctime = a->start_time;
3427 atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3429 /* If no time was provided, we're done. */
3430 if (!archive_entry_atime_is_set(a->entry)
3431 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
3432 && !archive_entry_birthtime_is_set(a->entry)
3434 && !archive_entry_mtime_is_set(a->entry))
3435 return (ARCHIVE_OK);
3437 if (archive_entry_atime_is_set(a->entry)) {
3438 atime = archive_entry_atime(a->entry);
3439 atime_nsec = archive_entry_atime_nsec(a->entry);
3441 if (archive_entry_birthtime_is_set(a->entry)) {
3442 birthtime = archive_entry_birthtime(a->entry);
3443 birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3445 if (archive_entry_mtime_is_set(a->entry)) {
3446 mtime = archive_entry_mtime(a->entry);
3447 mtime_nsec = archive_entry_mtime_nsec(a->entry);
3449 if (archive_entry_ctime_is_set(a->entry)) {
3450 cctime = archive_entry_ctime(a->entry);
3451 ctime_nsec = archive_entry_ctime_nsec(a->entry);
3454 return set_times(a, a->fd, a->mode, a->name,
3456 birthtime, birthtime_nsec,
3458 cctime, ctime_nsec);
3462 set_mode(struct archive_write_disk *a, int mode)
3466 mode &= 07777; /* Strip off file type bits. */
3468 if (a->todo & TODO_SGID_CHECK) {
3470 * If we don't know the GID is right, we must stat()
3471 * to verify it. We can't just check the GID of this
3472 * process, since systems sometimes set GID from
3473 * the enclosing dir or based on ACLs.
3475 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3477 if (a->pst->st_gid != a->gid) {
3479 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3481 * This is only an error if you
3482 * requested owner restore. If you
3483 * didn't, we'll try to restore
3484 * sgid/suid, but won't consider it a
3485 * problem if we can't.
3487 archive_set_error(&a->archive, -1,
3488 "Can't restore SGID bit");
3492 /* While we're here, double-check the UID. */
3493 if (a->pst->st_uid != a->uid
3494 && (a->todo & TODO_SUID)) {
3496 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3497 archive_set_error(&a->archive, -1,
3498 "Can't restore SUID bit");
3502 a->todo &= ~TODO_SGID_CHECK;
3503 a->todo &= ~TODO_SUID_CHECK;
3504 } else if (a->todo & TODO_SUID_CHECK) {
3506 * If we don't know the UID is right, we can just check
3507 * the user, since all systems set the file UID from
3510 if (a->user_uid != a->uid) {
3512 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3513 archive_set_error(&a->archive, -1,
3514 "Can't make file SUID");
3518 a->todo &= ~TODO_SUID_CHECK;
3521 if (S_ISLNK(a->mode)) {
3524 * If this is a symlink, use lchmod(). If the
3525 * platform doesn't support lchmod(), just skip it. A
3526 * platform that doesn't provide a way to set
3527 * permissions on symlinks probably ignores
3528 * permissions on symlinks, so a failure here has no
3531 if (lchmod(a->name, mode) != 0) {
3535 #if ENOTSUP != EOPNOTSUPP
3539 * if lchmod is defined but the platform
3540 * doesn't support it, silently ignore
3545 archive_set_error(&a->archive, errno,
3546 "Can't set permissions to 0%o", (int)mode);
3551 } else if (!S_ISDIR(a->mode)) {
3553 * If it's not a symlink and not a dir, then use
3554 * fchmod() or chmod(), depending on whether we have
3555 * an fd. Dirs get their perms set during the
3556 * post-extract fixup, which is handled elsewhere.
3560 r2 = fchmod(a->fd, mode);
3563 /* If this platform lacks fchmod(), then
3564 * we'll just use chmod(). */
3565 r2 = chmod(a->name, mode);
3568 archive_set_error(&a->archive, errno,
3569 "Can't set permissions to 0%o", (int)mode);
3577 set_fflags(struct archive_write_disk *a)
3579 struct fixup_entry *le;
3580 unsigned long set, clear;
3582 mode_t mode = archive_entry_mode(a->entry);
3584 * Make 'critical_flags' hold all file flags that can't be
3585 * immediately restored. For example, on BSD systems,
3586 * SF_IMMUTABLE prevents hardlinks from being created, so
3587 * should not be set until after any hardlinks are created. To
3588 * preserve some semblance of portability, this uses #ifdef
3589 * extensively. Ugly, but it works.
3591 * Yes, Virginia, this does create a security race. It's mitigated
3592 * somewhat by the practice of creating dirs 0700 until the extract
3593 * is done, but it would be nice if we could do more than that.
3594 * People restoring critical file systems should be wary of
3595 * other programs that might try to muck with files as they're
3598 const int critical_flags = 0
3611 #if defined(FS_APPEND_FL)
3613 #elif defined(EXT2_APPEND_FL)
3616 #if defined(FS_IMMUTABLE_FL)
3618 #elif defined(EXT2_IMMUTABLE_FL)
3621 #ifdef FS_JOURNAL_DATA_FL
3622 | FS_JOURNAL_DATA_FL
3626 if (a->todo & TODO_FFLAGS) {
3627 archive_entry_fflags(a->entry, &set, &clear);
3630 * The first test encourages the compiler to eliminate
3631 * all of this if it's not necessary.
3633 if ((critical_flags != 0) && (set & critical_flags)) {
3634 le = current_fixup(a, a->name);
3636 return (ARCHIVE_FATAL);
3637 le->fixup |= TODO_FFLAGS;
3638 le->fflags_set = set;
3639 /* Store the mode if it's not already there. */
3640 if ((le->fixup & TODO_MODE) == 0)
3643 r = set_fflags_platform(a, a->fd,
3644 a->name, mode, set, clear);
3645 if (r != ARCHIVE_OK)
3649 return (ARCHIVE_OK);
3653 clear_nochange_fflags(struct archive_write_disk *a)
3655 mode_t mode = archive_entry_mode(a->entry);
3656 const int nochange_flags = 0
3669 #ifdef EXT2_APPEND_FL
3672 #ifdef EXT2_IMMUTABLE_FL
3677 return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3682 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3684 * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3687 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3688 mode_t mode, unsigned long set, unsigned long clear)
3691 const int sf_mask = 0
3705 (void)mode; /* UNUSED */
3707 if (set == 0 && clear == 0)
3708 return (ARCHIVE_OK);
3711 * XXX Is the stat here really necessary? Or can I just use
3712 * the 'set' flags directly? In particular, I'm not sure
3713 * about the correct approach if we're overwriting an existing
3714 * file that already has flags on it. XXX
3716 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3719 a->st.st_flags &= ~clear;
3720 a->st.st_flags |= set;
3722 /* Only super-user may change SF_* flags */
3724 if (a->user_uid != 0)
3725 a->st.st_flags &= ~sf_mask;
3727 #ifdef HAVE_FCHFLAGS
3728 /* If platform has fchflags() and we were given an fd, use it. */
3729 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
3730 return (ARCHIVE_OK);
3733 * If we can't use the fd to set the flags, we'll use the
3734 * pathname to set flags. We prefer lchflags() but will use
3735 * chflags() if we must.
3737 #ifdef HAVE_LCHFLAGS
3738 if (lchflags(name, a->st.st_flags) == 0)
3739 return (ARCHIVE_OK);
3740 #elif defined(HAVE_CHFLAGS)
3741 if (S_ISLNK(a->st.st_mode)) {
3742 archive_set_error(&a->archive, errno,
3743 "Can't set file flags on symlink.");
3744 return (ARCHIVE_WARN);
3746 if (chflags(name, a->st.st_flags) == 0)
3747 return (ARCHIVE_OK);
3749 archive_set_error(&a->archive, errno,
3750 "Failed to set file flags");
3751 return (ARCHIVE_WARN);
3754 #elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \
3755 defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
3756 (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \
3757 defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
3759 * Linux uses ioctl() to read and write file flags.
3762 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3763 mode_t mode, unsigned long set, unsigned long clear)
3767 int newflags, oldflags;
3769 * Linux has no define for the flags that are only settable by
3770 * the root user. This code may seem a little complex, but
3771 * there seem to be some Linux systems that lack these
3772 * defines. (?) The code below degrades reasonably gracefully
3773 * if sf_mask is incomplete.
3775 const int sf_mask = 0
3776 #if defined(FS_IMMUTABLE_FL)
3778 #elif defined(EXT2_IMMUTABLE_FL)
3781 #if defined(FS_APPEND_FL)
3783 #elif defined(EXT2_APPEND_FL)
3786 #if defined(FS_JOURNAL_DATA_FL)
3787 | FS_JOURNAL_DATA_FL
3791 if (set == 0 && clear == 0)
3792 return (ARCHIVE_OK);
3793 /* Only regular files and dirs can have flags. */
3794 if (!S_ISREG(mode) && !S_ISDIR(mode))
3795 return (ARCHIVE_OK);
3797 /* If we weren't given an fd, open it ourselves. */
3799 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
3800 __archive_ensure_cloexec_flag(myfd);
3803 return (ARCHIVE_OK);
3806 * XXX As above, this would be way simpler if we didn't have
3807 * to read the current flags from disk. XXX
3811 /* Read the current file flags. */
3813 #ifdef FS_IOC_GETFLAGS
3821 /* Try setting the flags as given. */
3822 newflags = (oldflags & ~clear) | set;
3824 #ifdef FS_IOC_SETFLAGS
3834 /* If we couldn't set all the flags, try again with a subset. */
3835 newflags &= ~sf_mask;
3836 oldflags &= sf_mask;
3837 newflags |= oldflags;
3839 #ifdef FS_IOC_SETFLAGS
3847 /* We couldn't set the flags, so report the failure. */
3849 archive_set_error(&a->archive, errno,
3850 "Failed to set file flags");
3861 * Of course, some systems have neither BSD chflags() nor Linux' flags
3862 * support through ioctl().
3865 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3866 mode_t mode, unsigned long set, unsigned long clear)
3868 (void)a; /* UNUSED */
3869 (void)fd; /* UNUSED */
3870 (void)name; /* UNUSED */
3871 (void)mode; /* UNUSED */
3872 (void)set; /* UNUSED */
3873 (void)clear; /* UNUSED */
3874 return (ARCHIVE_OK);
3877 #endif /* __linux */
3879 #ifndef HAVE_COPYFILE_H
3880 /* Default is to simply drop Mac extended metadata. */
3882 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
3883 const void *metadata, size_t metadata_size)
3885 (void)a; /* UNUSED */
3886 (void)pathname; /* UNUSED */
3887 (void)metadata; /* UNUSED */
3888 (void)metadata_size; /* UNUSED */
3889 return (ARCHIVE_OK);
3893 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
3895 (void)a; /* UNUSED */
3896 (void)pathname; /* UNUSED */
3897 return (ARCHIVE_OK);
3902 * On Mac OS, we use copyfile() to unpack the metadata and
3903 * apply it to the target file.
3906 #if defined(HAVE_SYS_XATTR_H)
3908 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
3911 char *xattr_names = NULL, *xattr_val = NULL;
3912 int ret = ARCHIVE_OK, xattr_i;
3914 xattr_size = flistxattr(tmpfd, NULL, 0, 0);
3915 if (xattr_size == -1) {
3916 archive_set_error(&a->archive, errno,
3917 "Failed to read metadata(xattr)");
3921 xattr_names = malloc(xattr_size);
3922 if (xattr_names == NULL) {
3923 archive_set_error(&a->archive, ENOMEM,
3924 "Can't allocate memory for metadata(xattr)");
3925 ret = ARCHIVE_FATAL;
3928 xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
3929 if (xattr_size == -1) {
3930 archive_set_error(&a->archive, errno,
3931 "Failed to read metadata(xattr)");
3935 for (xattr_i = 0; xattr_i < xattr_size;
3936 xattr_i += strlen(xattr_names + xattr_i) + 1) {
3937 char *xattr_val_saved;
3941 s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
3943 archive_set_error(&a->archive, errno,
3944 "Failed to get metadata(xattr)");
3948 xattr_val_saved = xattr_val;
3949 xattr_val = realloc(xattr_val, s);
3950 if (xattr_val == NULL) {
3951 archive_set_error(&a->archive, ENOMEM,
3952 "Failed to get metadata(xattr)");
3954 free(xattr_val_saved);
3957 s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
3959 archive_set_error(&a->archive, errno,
3960 "Failed to get metadata(xattr)");
3964 f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
3966 archive_set_error(&a->archive, errno,
3967 "Failed to get metadata(xattr)");
3980 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
3982 #ifndef HAVE_SYS_ACL_H
3985 acl_t acl, dfacl = NULL;
3986 int acl_r, ret = ARCHIVE_OK;
3988 acl = acl_get_fd(tmpfd);
3990 if (errno == ENOENT)
3991 /* There are not any ACLs. */
3993 archive_set_error(&a->archive, errno,
3994 "Failed to get metadata(acl)");
3998 dfacl = acl_dup(acl);
3999 acl_r = acl_set_fd(dffd, dfacl);
4001 archive_set_error(&a->archive, errno,
4002 "Failed to get metadata(acl)");
4016 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4018 struct archive_string tmpdatafork;
4021 archive_string_init(&tmpdatafork);
4022 archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
4023 tmpfd = mkstemp(tmpdatafork.s);
4025 archive_set_error(&a->archive, errno,
4026 "Failed to mkstemp");
4027 archive_string_free(&tmpdatafork);
4030 if (copyfile(pathname, tmpdatafork.s, 0,
4031 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4032 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4033 archive_set_error(&a->archive, errno,
4034 "Failed to restore metadata");
4038 unlink(tmpdatafork.s);
4039 archive_string_free(&tmpdatafork);
4044 copy_metadata(struct archive_write_disk *a, const char *metadata,
4045 const char *datafork, int datafork_compressed)
4047 int ret = ARCHIVE_OK;
4049 if (datafork_compressed) {
4052 tmpfd = create_tempdatafork(a, metadata);
4054 return (ARCHIVE_WARN);
4057 * Do not open the data fork compressed by HFS+ compression
4058 * with at least a writing mode(O_RDWR or O_WRONLY). it
4059 * makes the data fork uncompressed.
4061 dffd = open(datafork, 0);
4063 archive_set_error(&a->archive, errno,
4064 "Failed to open the data fork for metadata");
4066 return (ARCHIVE_WARN);
4069 #if defined(HAVE_SYS_XATTR_H)
4070 ret = copy_xattrs(a, tmpfd, dffd);
4071 if (ret == ARCHIVE_OK)
4073 ret = copy_acls(a, tmpfd, dffd);
4077 if (copyfile(metadata, datafork, 0,
4078 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4079 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4080 archive_set_error(&a->archive, errno,
4081 "Failed to restore metadata");
4089 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4090 const void *metadata, size_t metadata_size)
4092 struct archive_string tmp;
4095 int ret = ARCHIVE_OK;
4097 /* This would be simpler if copyfile() could just accept the
4098 * metadata as a block of memory; then we could sidestep this
4099 * silly dance of writing the data to disk just so that
4100 * copyfile() can read it back in again. */
4101 archive_string_init(&tmp);
4102 archive_strcpy(&tmp, pathname);
4103 archive_strcat(&tmp, ".XXXXXX");
4104 fd = mkstemp(tmp.s);
4107 archive_set_error(&a->archive, errno,
4108 "Failed to restore metadata");
4109 archive_string_free(&tmp);
4110 return (ARCHIVE_WARN);
4112 written = write(fd, metadata, metadata_size);
4114 if ((size_t)written != metadata_size) {
4115 archive_set_error(&a->archive, errno,
4116 "Failed to restore metadata");
4121 #if defined(UF_COMPRESSED)
4122 if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
4123 (ret = lazy_stat(a)) == ARCHIVE_OK)
4124 compressed = a->st.st_flags & UF_COMPRESSED;
4128 ret = copy_metadata(a, tmp.s, pathname, compressed);
4131 archive_string_free(&tmp);
4136 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4141 struct archive_string datafork;
4142 int fd = -1, ret = ARCHIVE_OK;
4144 archive_string_init(&datafork);
4145 /* Check if the current file name is a type of the resource
4147 p = strrchr(pathname, '/');
4152 if (p[0] != '.' || p[1] != '_')
4153 goto skip_appledouble;
4156 * Check if the data fork file exists.
4158 * TODO: Check if this write disk object has handled it.
4160 archive_strncpy(&datafork, pathname, p - pathname);
4161 archive_strcat(&datafork, p + 2);
4162 if (lstat(datafork.s, &st) == -1 ||
4163 (st.st_mode & AE_IFMT) != AE_IFREG)
4164 goto skip_appledouble;
4167 * Check if the file is in the AppleDouble form.
4169 fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4170 __archive_ensure_cloexec_flag(fd);
4172 archive_set_error(&a->archive, errno,
4173 "Failed to open a restoring file");
4175 goto skip_appledouble;
4177 if (read(fd, buff, 8) == -1) {
4178 archive_set_error(&a->archive, errno,
4179 "Failed to read a restoring file");
4182 goto skip_appledouble;
4185 /* Check AppleDouble Magic Code. */
4186 if (archive_be32dec(buff) != 0x00051607)
4187 goto skip_appledouble;
4188 /* Check AppleDouble Version. */
4189 if (archive_be32dec(buff+4) != 0x00020000)
4190 goto skip_appledouble;
4192 ret = copy_metadata(a, pathname, datafork.s,
4193 #if defined(UF_COMPRESSED)
4194 st.st_flags & UF_COMPRESSED);
4198 if (ret == ARCHIVE_OK) {
4203 archive_string_free(&datafork);
4208 #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4210 * Restore extended attributes - Linux, Darwin and AIX implementations:
4211 * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4214 set_xattrs(struct archive_write_disk *a)
4216 struct archive_entry *entry = a->entry;
4217 static int warning_done = 0;
4218 int ret = ARCHIVE_OK;
4219 int i = archive_entry_xattr_reset(entry);
4225 archive_entry_xattr_next(entry, &name, &value, &size);
4227 strncmp(name, "xfsroot.", 8) != 0 &&
4228 strncmp(name, "system.", 7) != 0) {
4231 #if ARCHIVE_XATTR_LINUX
4232 e = fsetxattr(a->fd, name, value, size, 0);
4233 #elif ARCHIVE_XATTR_DARWIN
4234 e = fsetxattr(a->fd, name, value, size, 0, 0);
4235 #elif ARCHIVE_XATTR_AIX
4236 e = fsetea(a->fd, name, value, size, 0);
4239 #if ARCHIVE_XATTR_LINUX
4240 e = lsetxattr(archive_entry_pathname(entry),
4241 name, value, size, 0);
4242 #elif ARCHIVE_XATTR_DARWIN
4243 e = setxattr(archive_entry_pathname(entry),
4244 name, value, size, 0, XATTR_NOFOLLOW);
4245 #elif ARCHIVE_XATTR_AIX
4246 e = lsetea(archive_entry_pathname(entry),
4247 name, value, size, 0);
4251 if (errno == ENOTSUP || errno == ENOSYS) {
4252 if (!warning_done) {
4254 archive_set_error(&a->archive,
4256 "Cannot restore extended "
4257 "attributes on this file "
4261 archive_set_error(&a->archive, errno,
4262 "Failed to set extended attribute");
4266 archive_set_error(&a->archive,
4267 ARCHIVE_ERRNO_FILE_FORMAT,
4268 "Invalid extended attribute encountered");
4274 #elif ARCHIVE_XATTR_FREEBSD
4276 * Restore extended attributes - FreeBSD implementation
4279 set_xattrs(struct archive_write_disk *a)
4281 struct archive_entry *entry = a->entry;
4282 static int warning_done = 0;
4283 int ret = ARCHIVE_OK;
4284 int i = archive_entry_xattr_reset(entry);
4290 archive_entry_xattr_next(entry, &name, &value, &size);
4295 if (strncmp(name, "user.", 5) == 0) {
4296 /* "user." attributes go to user namespace */
4298 namespace = EXTATTR_NAMESPACE_USER;
4300 /* Warn about other extended attributes. */
4301 archive_set_error(&a->archive,
4302 ARCHIVE_ERRNO_FILE_FORMAT,
4303 "Can't restore extended attribute ``%s''",
4311 e = extattr_set_fd(a->fd, namespace, name,
4314 e = extattr_set_link(
4315 archive_entry_pathname(entry), namespace,
4318 if (e != (ssize_t)size) {
4319 if (errno == ENOTSUP || errno == ENOSYS) {
4320 if (!warning_done) {
4322 archive_set_error(&a->archive,
4324 "Cannot restore extended "
4325 "attributes on this file "
4329 archive_set_error(&a->archive, errno,
4330 "Failed to set extended attribute");
4341 * Restore extended attributes - stub implementation for unsupported systems
4344 set_xattrs(struct archive_write_disk *a)
4346 static int warning_done = 0;
4348 /* If there aren't any extended attributes, then it's okay not
4349 * to extract them, otherwise, issue a single warning. */
4350 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4352 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4353 "Cannot restore extended attributes on this system");
4354 return (ARCHIVE_WARN);
4356 /* Warning was already emitted; suppress further warnings. */
4357 return (ARCHIVE_OK);
4362 * Test if file on disk is older than entry.
4365 older(struct stat *st, struct archive_entry *entry)
4367 /* First, test the seconds and return if we have a definite answer. */
4368 /* Definitely older. */
4369 if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry)))
4371 /* Definitely younger. */
4372 if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4374 /* If this platform supports fractional seconds, try those. */
4375 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4376 /* Definitely older. */
4377 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4379 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4380 /* Definitely older. */
4381 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4383 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4385 if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4387 #elif HAVE_STRUCT_STAT_ST_UMTIME
4389 if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4391 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4393 if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4396 /* This system doesn't have high-res timestamps. */
4398 /* Same age or newer, so not older. */
4402 #ifndef ARCHIVE_ACL_SUPPORT
4404 archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4405 struct archive_acl *abstract_acl, __LA_MODE_T mode)
4407 (void)a; /* UNUSED */
4408 (void)fd; /* UNUSED */
4409 (void)name; /* UNUSED */
4410 (void)abstract_acl; /* UNUSED */
4411 (void)mode; /* UNUSED */
4412 return (ARCHIVE_OK);
4416 #endif /* !_WIN32 || __CYGWIN__ */