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 char *tmpname; /* Temporary name * */
257 struct archive_string _tmpname_data; /* backing store for 'tmpname' */
258 /* Tasks remaining for this object. */
260 /* Tasks deferred until end-of-archive. */
262 /* Options requested by the client. */
264 /* Handle for the file we're restoring. */
266 /* Current offset for writing data to the file. */
268 /* Last offset actually written to disk. */
270 /* Total bytes actually written to files. */
271 int64_t total_bytes_written;
272 /* Maximum size of file, -1 if unknown. */
274 /* Dir we were in before this restore; only for deep paths. */
276 /* Mode we should use for this entry; affected by _PERM and umask. */
278 /* UID/GID to use in restoring this entry. */
284 /* Xattr "com.apple.decmpfs". */
285 uint32_t decmpfs_attr_size;
286 unsigned char *decmpfs_header_p;
287 /* ResourceFork set options used for fsetxattr. */
288 int rsrc_xattr_options;
289 /* Xattr "com.apple.ResourceFork". */
290 unsigned char *resource_fork;
291 size_t resource_fork_allocated_size;
292 unsigned int decmpfs_block_count;
293 uint32_t *decmpfs_block_info;
294 /* Buffer for compressed data. */
295 unsigned char *compressed_buffer;
296 size_t compressed_buffer_size;
297 size_t compressed_buffer_remaining;
298 /* The offset of the ResourceFork where compressed data will
300 uint32_t compressed_rsrc_position;
301 uint32_t compressed_rsrc_position_v;
302 /* Buffer for uncompressed data. */
303 char *uncompressed_buffer;
304 size_t block_remaining_bytes;
305 size_t file_remaining_bytes;
309 int decmpfs_compression_level;
314 * Default mode for dirs created automatically (will be modified by umask).
315 * Note that POSIX specifies 0777 for implicitly-created dirs, "modified
316 * by the process' file creation mask."
318 #define DEFAULT_DIR_MODE 0777
320 * Dir modes are restored in two steps: During the extraction, the permissions
321 * in the archive are modified to match the following limits. During
322 * the post-extract fixup pass, the permissions from the archive are
325 #define MINIMUM_DIR_MODE 0700
326 #define MAXIMUM_DIR_MODE 0775
329 * Maximum uncompressed size of a decmpfs block.
331 #define MAX_DECMPFS_BLOCK_SIZE (64 * 1024)
333 * HFS+ compression type.
335 #define CMP_XATTR 3/* Compressed data in xattr. */
336 #define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */
338 * HFS+ compression resource fork.
340 #define RSRC_H_SIZE 260 /* Base size of Resource fork header. */
341 #define RSRC_F_SIZE 50 /* Size of Resource fork footer. */
342 /* Size to write compressed data to resource fork. */
343 #define COMPRESSED_W_SIZE (64 * 1024)
344 /* decmpfs definitions. */
345 #define MAX_DECMPFS_XATTR_SIZE 3802
346 #ifndef DECMPFS_XATTR_NAME
347 #define DECMPFS_XATTR_NAME "com.apple.decmpfs"
349 #define DECMPFS_MAGIC 0x636d7066
350 #define DECMPFS_COMPRESSION_MAGIC 0
351 #define DECMPFS_COMPRESSION_TYPE 4
352 #define DECMPFS_UNCOMPRESSED_SIZE 8
353 #define DECMPFS_HEADER_SIZE 16
355 #define HFS_BLOCKS(s) ((s) >> 12)
358 static int la_opendirat(int, const char *);
359 static int la_mktemp(struct archive_write_disk *);
360 static void fsobj_error(int *, struct archive_string *, int, const char *,
362 static int check_symlinks_fsobj(char *, int *, struct archive_string *,
364 static int check_symlinks(struct archive_write_disk *);
365 static int create_filesystem_object(struct archive_write_disk *);
366 static struct fixup_entry *current_fixup(struct archive_write_disk *,
367 const char *pathname);
368 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
369 static void edit_deep_directories(struct archive_write_disk *ad);
371 static int cleanup_pathname_fsobj(char *, int *, struct archive_string *,
373 static int cleanup_pathname(struct archive_write_disk *);
374 static int create_dir(struct archive_write_disk *, char *);
375 static int create_parent_dir(struct archive_write_disk *, char *);
376 static ssize_t hfs_write_data_block(struct archive_write_disk *,
377 const char *, size_t);
378 static int fixup_appledouble(struct archive_write_disk *, const char *);
379 static int older(struct stat *, struct archive_entry *);
380 static int restore_entry(struct archive_write_disk *);
381 static int set_mac_metadata(struct archive_write_disk *, const char *,
382 const void *, size_t);
383 static int set_xattrs(struct archive_write_disk *);
384 static int clear_nochange_fflags(struct archive_write_disk *);
385 static int set_fflags(struct archive_write_disk *);
386 static int set_fflags_platform(struct archive_write_disk *, int fd,
387 const char *name, mode_t mode,
388 unsigned long fflags_set, unsigned long fflags_clear);
389 static int set_ownership(struct archive_write_disk *);
390 static int set_mode(struct archive_write_disk *, int mode);
391 static int set_time(int, int, const char *, time_t, long, time_t, long);
392 static int set_times(struct archive_write_disk *, int, int, const char *,
393 time_t, long, time_t, long, time_t, long, time_t, long);
394 static int set_times_from_entry(struct archive_write_disk *);
395 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
396 static ssize_t write_data_block(struct archive_write_disk *,
397 const char *, size_t);
399 static struct archive_vtable *archive_write_disk_vtable(void);
401 static int _archive_write_disk_close(struct archive *);
402 static int _archive_write_disk_free(struct archive *);
403 static int _archive_write_disk_header(struct archive *,
404 struct archive_entry *);
405 static int64_t _archive_write_disk_filter_bytes(struct archive *, int);
406 static int _archive_write_disk_finish_entry(struct archive *);
407 static ssize_t _archive_write_disk_data(struct archive *, const void *,
409 static ssize_t _archive_write_disk_data_block(struct archive *, const void *,
413 la_mktemp(struct archive_write_disk *a)
418 archive_string_empty(&a->_tmpname_data);
419 archive_string_sprintf(&a->_tmpname_data, "%s.XXXXXX", a->name);
420 a->tmpname = a->_tmpname_data.s;
422 fd = __archive_mkstemp(a->tmpname);
426 mode = a->mode & 0777 & ~a->user_umask;
427 if (fchmod(fd, mode) == -1) {
437 la_opendirat(int fd, const char *path) {
438 const int flags = O_CLOEXEC
439 #if defined(O_BINARY)
442 #if defined(O_DIRECTORY)
447 #elif defined(O_SEARCH)
449 #elif defined(__FreeBSD__) && defined(O_EXEC)
456 #if !defined(HAVE_OPENAT)
457 if (fd != AT_FDCWD) {
461 return (open(path, flags));
463 return (openat(fd, path, flags));
468 lazy_stat(struct archive_write_disk *a)
470 if (a->pst != NULL) {
471 /* Already have stat() data available. */
475 if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
481 * XXX At this point, symlinks should not be hit, otherwise
482 * XXX a race occurred. Do we want to check explicitly for that?
484 if (lstat(a->name, &a->st) == 0) {
488 archive_set_error(&a->archive, errno, "Couldn't stat file");
489 return (ARCHIVE_WARN);
492 static struct archive_vtable *
493 archive_write_disk_vtable(void)
495 static struct archive_vtable av;
496 static int inited = 0;
499 av.archive_close = _archive_write_disk_close;
500 av.archive_filter_bytes = _archive_write_disk_filter_bytes;
501 av.archive_free = _archive_write_disk_free;
502 av.archive_write_header = _archive_write_disk_header;
503 av.archive_write_finish_entry
504 = _archive_write_disk_finish_entry;
505 av.archive_write_data = _archive_write_disk_data;
506 av.archive_write_data_block = _archive_write_disk_data_block;
513 _archive_write_disk_filter_bytes(struct archive *_a, int n)
515 struct archive_write_disk *a = (struct archive_write_disk *)_a;
516 (void)n; /* UNUSED */
517 if (n == -1 || n == 0)
518 return (a->total_bytes_written);
524 archive_write_disk_set_options(struct archive *_a, int flags)
526 struct archive_write_disk *a = (struct archive_write_disk *)_a;
534 * Extract this entry to disk.
536 * TODO: Validate hardlinks. According to the standards, we're
537 * supposed to check each extracted hardlink and squawk if it refers
538 * to a file that we didn't restore. I'm not entirely convinced this
539 * is a good idea, but more importantly: Is there any way to validate
540 * hardlinks without keeping a complete list of filenames from the
541 * entire archive?? Ugh.
545 _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
547 struct archive_write_disk *a = (struct archive_write_disk *)_a;
548 struct fixup_entry *fe;
549 const char *linkname;
552 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
553 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
554 "archive_write_disk_header");
555 archive_clear_error(&a->archive);
556 if (a->archive.state & ARCHIVE_STATE_DATA) {
557 r = _archive_write_disk_finish_entry(&a->archive);
558 if (r == ARCHIVE_FATAL)
562 /* Set up for this particular entry. */
564 a->current_fixup = NULL;
567 archive_entry_free(a->entry);
570 a->entry = archive_entry_clone(entry);
575 a->uid = a->user_uid;
576 a->mode = archive_entry_mode(a->entry);
577 if (archive_entry_size_is_set(a->entry))
578 a->filesize = archive_entry_size(a->entry);
581 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
582 a->name = a->_name_data.s;
583 archive_clear_error(&a->archive);
586 * Clean up the requested path. This is necessary for correct
587 * dir restores; the dir restore logic otherwise gets messed
588 * up by nonsense like "dir/.".
590 ret = cleanup_pathname(a);
591 if (ret != ARCHIVE_OK)
595 * Check if we have a hardlink that points to itself.
597 linkname = archive_entry_hardlink(a->entry);
598 if (linkname != NULL && strcmp(a->name, linkname) == 0) {
599 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
600 "Skipping hardlink pointing to itself: %s",
602 return (ARCHIVE_WARN);
606 * Query the umask so we get predictable mode settings.
607 * This gets done on every call to _write_header in case the
608 * user edits their umask during the extraction for some
611 umask(a->user_umask = umask(0));
613 /* Figure out what we need to do for this entry. */
614 a->todo = TODO_MODE_BASE;
615 if (a->flags & ARCHIVE_EXTRACT_PERM) {
616 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
618 * SGID requires an extra "check" step because we
619 * cannot easily predict the GID that the system will
620 * assign. (Different systems assign GIDs to files
621 * based on a variety of criteria, including process
622 * credentials and the gid of the enclosing
623 * directory.) We can only restore the SGID bit if
624 * the file has the right GID, and we only know the
625 * GID if we either set it (see set_ownership) or if
626 * we've actually called stat() on the file after it
627 * was restored. Since there are several places at
628 * which we might verify the GID, we need a TODO bit
631 if (a->mode & S_ISGID)
632 a->todo |= TODO_SGID | TODO_SGID_CHECK;
634 * Verifying the SUID is simpler, but can still be
635 * done in multiple ways, hence the separate "check" bit.
637 if (a->mode & S_ISUID)
638 a->todo |= TODO_SUID | TODO_SUID_CHECK;
641 * User didn't request full permissions, so don't
642 * restore SUID, SGID bits and obey umask.
647 a->mode &= ~a->user_umask;
649 if (a->flags & ARCHIVE_EXTRACT_OWNER)
650 a->todo |= TODO_OWNER;
651 if (a->flags & ARCHIVE_EXTRACT_TIME)
652 a->todo |= TODO_TIMES;
653 if (a->flags & ARCHIVE_EXTRACT_ACL) {
654 #if ARCHIVE_ACL_DARWIN
656 * On MacOS, platform ACLs get stored in mac_metadata, too.
657 * If we intend to extract mac_metadata and it is present
658 * we skip extracting libarchive NFSv4 ACLs.
660 size_t metadata_size;
662 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
663 archive_entry_mac_metadata(a->entry,
664 &metadata_size) == NULL || metadata_size == 0)
666 #if ARCHIVE_ACL_LIBRICHACL
668 * RichACLs are stored in an extended attribute.
669 * If we intend to extract extended attributes and have this
670 * attribute we skip extracting libarchive NFSv4 ACLs.
672 short extract_acls = 1;
673 if (a->flags & ARCHIVE_EXTRACT_XATTR && (
674 archive_entry_acl_types(a->entry) &
675 ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
676 const char *attr_name;
677 const void *attr_value;
679 int i = archive_entry_xattr_reset(a->entry);
681 archive_entry_xattr_next(a->entry, &attr_name,
682 &attr_value, &attr_size);
683 if (attr_name != NULL && attr_value != NULL &&
684 attr_size > 0 && strcmp(attr_name,
685 "trusted.richacl") == 0) {
693 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
696 if (archive_entry_filetype(a->entry) == AE_IFDIR)
697 a->deferred |= TODO_ACLS;
699 a->todo |= TODO_ACLS;
700 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
704 if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
705 if (archive_entry_filetype(a->entry) == AE_IFDIR)
706 a->deferred |= TODO_MAC_METADATA;
708 a->todo |= TODO_MAC_METADATA;
710 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
711 if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
712 unsigned long set, clear;
713 archive_entry_fflags(a->entry, &set, &clear);
714 if ((set & ~clear) & UF_COMPRESSED) {
715 a->todo |= TODO_HFS_COMPRESSION;
716 a->decmpfs_block_count = (unsigned)-1;
719 if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
720 (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
721 a->todo |= TODO_HFS_COMPRESSION;
722 a->decmpfs_block_count = (unsigned)-1;
727 /* Check if the current file name is a type of the
728 * resource fork file. */
729 p = strrchr(a->name, '/');
734 if (p[0] == '.' && p[1] == '_') {
735 /* Do not compress "._XXX" files. */
736 a->todo &= ~TODO_HFS_COMPRESSION;
738 a->todo |= TODO_APPLEDOUBLE;
743 if (a->flags & ARCHIVE_EXTRACT_XATTR) {
744 #if ARCHIVE_XATTR_DARWIN
746 * On MacOS, extended attributes get stored in mac_metadata,
747 * too. If we intend to extract mac_metadata and it is present
748 * we skip extracting extended attributes.
750 size_t metadata_size;
752 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
753 archive_entry_mac_metadata(a->entry,
754 &metadata_size) == NULL || metadata_size == 0)
756 a->todo |= TODO_XATTR;
758 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
759 a->todo |= TODO_FFLAGS;
760 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
761 ret = check_symlinks(a);
762 if (ret != ARCHIVE_OK)
765 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
766 /* If path exceeds PATH_MAX, shorten the path. */
767 edit_deep_directories(a);
770 ret = restore_entry(a);
772 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
774 * Check if the filesystem the file is restoring on supports
775 * HFS+ Compression. If not, cancel HFS+ Compression.
777 if (a->todo | TODO_HFS_COMPRESSION) {
779 * NOTE: UF_COMPRESSED is ignored even if the filesystem
780 * supports HFS+ Compression because the file should
781 * have at least an extended attribute "com.apple.decmpfs"
782 * before the flag is set to indicate that the file have
783 * been compressed. If the filesystem does not support
784 * HFS+ Compression the system call will fail.
786 if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
787 a->todo &= ~TODO_HFS_COMPRESSION;
792 * TODO: There are rumours that some extended attributes must
793 * be restored before file data is written. If this is true,
794 * then we either need to write all extended attributes both
795 * before and after restoring the data, or find some rule for
796 * determining which must go first and which last. Due to the
797 * many ways people are using xattrs, this may prove to be an
798 * intractable problem.
802 /* If we changed directory above, restore it here. */
803 if (a->restore_pwd >= 0) {
804 r = fchdir(a->restore_pwd);
806 archive_set_error(&a->archive, errno,
810 close(a->restore_pwd);
816 * Fixup uses the unedited pathname from archive_entry_pathname(),
817 * because it is relative to the base dir and the edited path
818 * might be relative to some intermediate dir as a result of the
819 * deep restore logic.
821 if (a->deferred & TODO_MODE) {
822 fe = current_fixup(a, archive_entry_pathname(entry));
824 return (ARCHIVE_FATAL);
825 fe->fixup |= TODO_MODE_BASE;
829 if ((a->deferred & TODO_TIMES)
830 && (archive_entry_mtime_is_set(entry)
831 || archive_entry_atime_is_set(entry))) {
832 fe = current_fixup(a, archive_entry_pathname(entry));
834 return (ARCHIVE_FATAL);
836 fe->fixup |= TODO_TIMES;
837 if (archive_entry_atime_is_set(entry)) {
838 fe->atime = archive_entry_atime(entry);
839 fe->atime_nanos = archive_entry_atime_nsec(entry);
841 /* If atime is unset, use start time. */
842 fe->atime = a->start_time;
845 if (archive_entry_mtime_is_set(entry)) {
846 fe->mtime = archive_entry_mtime(entry);
847 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
849 /* If mtime is unset, use start time. */
850 fe->mtime = a->start_time;
853 if (archive_entry_birthtime_is_set(entry)) {
854 fe->birthtime = archive_entry_birthtime(entry);
855 fe->birthtime_nanos = archive_entry_birthtime_nsec(
858 /* If birthtime is unset, use mtime. */
859 fe->birthtime = fe->mtime;
860 fe->birthtime_nanos = fe->mtime_nanos;
864 if (a->deferred & TODO_ACLS) {
865 fe = current_fixup(a, archive_entry_pathname(entry));
867 return (ARCHIVE_FATAL);
868 fe->fixup |= TODO_ACLS;
869 archive_acl_copy(&fe->acl, archive_entry_acl(entry));
872 if (a->deferred & TODO_MAC_METADATA) {
873 const void *metadata;
874 size_t metadata_size;
875 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
876 if (metadata != NULL && metadata_size > 0) {
877 fe = current_fixup(a, archive_entry_pathname(entry));
879 return (ARCHIVE_FATAL);
880 fe->mac_metadata = malloc(metadata_size);
881 if (fe->mac_metadata != NULL) {
882 memcpy(fe->mac_metadata, metadata,
884 fe->mac_metadata_size = metadata_size;
885 fe->fixup |= TODO_MAC_METADATA;
890 if (a->deferred & TODO_FFLAGS) {
891 fe = current_fixup(a, archive_entry_pathname(entry));
893 return (ARCHIVE_FATAL);
894 fe->fixup |= TODO_FFLAGS;
895 /* TODO: Complete this.. defer fflags from below. */
898 /* We've created the object and are ready to pour data into it. */
899 if (ret >= ARCHIVE_WARN)
900 a->archive.state = ARCHIVE_STATE_DATA;
902 * If it's not open, tell our client not to try writing.
903 * In particular, dirs, links, etc, don't get written to.
906 archive_entry_set_size(entry, 0);
914 archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
916 struct archive_write_disk *a = (struct archive_write_disk *)_a;
917 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
918 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
919 a->skip_file_set = 1;
920 a->skip_file_dev = d;
921 a->skip_file_ino = i;
926 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
928 uint64_t start_size = size;
929 ssize_t bytes_written = 0;
930 ssize_t block_size = 0, bytes_to_write;
935 if (a->filesize == 0 || a->fd < 0) {
936 archive_set_error(&a->archive, 0,
937 "Attempt to write to an empty file");
938 return (ARCHIVE_WARN);
941 if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
942 #if HAVE_STRUCT_STAT_ST_BLKSIZE
944 if ((r = lazy_stat(a)) != ARCHIVE_OK)
946 block_size = a->pst->st_blksize;
948 /* XXX TODO XXX Is there a more appropriate choice here ? */
949 /* This needn't match the filesystem allocation size. */
950 block_size = 16*1024;
954 /* If this write would run beyond the file size, truncate it. */
955 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
956 start_size = size = (size_t)(a->filesize - a->offset);
958 /* Write the data. */
960 if (block_size == 0) {
961 bytes_to_write = size;
963 /* We're sparsifying the file. */
967 /* Skip leading zero bytes. */
968 for (p = buff, end = buff + size; p < end; ++p) {
972 a->offset += p - buff;
978 /* Calculate next block boundary after offset. */
980 = (a->offset / block_size + 1) * block_size;
982 /* If the adjusted write would cross block boundary,
983 * truncate it to the block boundary. */
984 bytes_to_write = size;
985 if (a->offset + bytes_to_write > block_end)
986 bytes_to_write = block_end - a->offset;
988 /* Seek if necessary to the specified offset. */
989 if (a->offset != a->fd_offset) {
990 if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
991 archive_set_error(&a->archive, errno,
993 return (ARCHIVE_FATAL);
995 a->fd_offset = a->offset;
997 bytes_written = write(a->fd, buff, bytes_to_write);
998 if (bytes_written < 0) {
999 archive_set_error(&a->archive, errno, "Write failed");
1000 return (ARCHIVE_WARN);
1002 buff += bytes_written;
1003 size -= bytes_written;
1004 a->total_bytes_written += bytes_written;
1005 a->offset += bytes_written;
1006 a->fd_offset = a->offset;
1008 return (start_size - size);
1011 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
1012 && defined(HAVE_ZLIB_H)
1015 * Set UF_COMPRESSED file flag.
1016 * This have to be called after hfs_write_decmpfs() because if the
1017 * file does not have "com.apple.decmpfs" xattr the flag is ignored.
1020 hfs_set_compressed_fflag(struct archive_write_disk *a)
1024 if ((r = lazy_stat(a)) != ARCHIVE_OK)
1027 a->st.st_flags |= UF_COMPRESSED;
1028 if (fchflags(a->fd, a->st.st_flags) != 0) {
1029 archive_set_error(&a->archive, errno,
1030 "Failed to set UF_COMPRESSED file flag");
1031 return (ARCHIVE_WARN);
1033 return (ARCHIVE_OK);
1037 * HFS+ Compression decmpfs
1039 * +------------------------------+ +0
1040 * | Magic(LE 4 bytes) |
1041 * +------------------------------+
1042 * | Type(LE 4 bytes) |
1043 * +------------------------------+
1044 * | Uncompressed size(LE 8 bytes)|
1045 * +------------------------------+ +16
1047 * | Compressed data |
1048 * | (Placed only if Type == 3) |
1050 * +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE
1052 * Type is 3: decmpfs has compressed data.
1053 * Type is 4: Resource Fork has compressed data.
1056 * Write "com.apple.decmpfs"
1059 hfs_write_decmpfs(struct archive_write_disk *a)
1062 uint32_t compression_type;
1064 r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1065 a->decmpfs_attr_size, 0, 0);
1067 archive_set_error(&a->archive, errno,
1068 "Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
1069 compression_type = archive_le32dec(
1070 &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
1071 if (compression_type == CMP_RESOURCE_FORK)
1072 fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
1073 XATTR_SHOWCOMPRESSION);
1074 return (ARCHIVE_WARN);
1076 return (ARCHIVE_OK);
1080 * HFS+ Compression Resource Fork
1082 * +-----------------------------+
1083 * | Header(260 bytes) |
1084 * +-----------------------------+
1085 * | Block count(LE 4 bytes) |
1086 * +-----------------------------+ --+
1087 * +-- | Offset (LE 4 bytes) | |
1088 * | | [distance from Block count] | | Block 0
1089 * | +-----------------------------+ |
1090 * | | Compressed size(LE 4 bytes) | |
1091 * | +-----------------------------+ --+
1093 * | | .................. |
1095 * | +-----------------------------+ --+
1096 * | | Offset (LE 4 bytes) | |
1097 * | +-----------------------------+ | Block (Block count -1)
1098 * | | Compressed size(LE 4 bytes) | |
1099 * +-> +-----------------------------+ --+
1100 * | Compressed data(n bytes) | Block 0
1101 * +-----------------------------+
1103 * | .................. |
1105 * +-----------------------------+
1106 * | Compressed data(n bytes) | Block (Block count -1)
1107 * +-----------------------------+
1108 * | Footer(50 bytes) |
1109 * +-----------------------------+
1113 * Write the header of "com.apple.ResourceFork"
1116 hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1117 size_t bytes, uint32_t position)
1121 ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1122 position, a->rsrc_xattr_options);
1124 archive_set_error(&a->archive, errno,
1125 "Cannot restore xattr: %s at %u pos %u bytes",
1126 XATTR_RESOURCEFORK_NAME,
1129 return (ARCHIVE_WARN);
1131 a->rsrc_xattr_options &= ~XATTR_CREATE;
1132 return (ARCHIVE_OK);
1136 hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1140 ret = hfs_write_resource_fork(a, a->compressed_buffer,
1141 bytes_compressed, a->compressed_rsrc_position);
1142 if (ret == ARCHIVE_OK)
1143 a->compressed_rsrc_position += bytes_compressed;
1148 hfs_write_resource_fork_header(struct archive_write_disk *a)
1150 unsigned char *buff;
1151 uint32_t rsrc_bytes;
1152 uint32_t rsrc_header_bytes;
1155 * Write resource fork header + block info.
1157 buff = a->resource_fork;
1158 rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1160 RSRC_H_SIZE + /* Header base size. */
1161 4 + /* Block count. */
1162 (a->decmpfs_block_count * 8);/* Block info */
1163 archive_be32enc(buff, 0x100);
1164 archive_be32enc(buff + 4, rsrc_bytes);
1165 archive_be32enc(buff + 8, rsrc_bytes - 256);
1166 archive_be32enc(buff + 12, 0x32);
1167 memset(buff + 16, 0, 240);
1168 archive_be32enc(buff + 256, rsrc_bytes - 260);
1169 return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
1173 hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1175 static const char rsrc_footer[RSRC_F_SIZE] = {
1176 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1177 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1178 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1179 0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm',
1180 'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
1181 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1184 if (buff_size < sizeof(rsrc_footer))
1186 memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1187 return (sizeof(rsrc_footer));
1191 hfs_reset_compressor(struct archive_write_disk *a)
1195 if (a->stream_valid)
1196 ret = deflateReset(&a->stream);
1198 ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1201 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1202 "Failed to initialize compressor");
1203 return (ARCHIVE_FATAL);
1205 a->stream_valid = 1;
1207 return (ARCHIVE_OK);
1211 hfs_decompress(struct archive_write_disk *a)
1213 uint32_t *block_info;
1214 unsigned int block_count;
1215 uint32_t data_pos, data_size;
1217 ssize_t bytes_written, bytes_to_write;
1220 block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1221 block_count = archive_le32dec(block_info++);
1222 while (block_count--) {
1223 data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
1224 data_size = archive_le32dec(block_info++);
1225 r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
1226 a->compressed_buffer, data_size, data_pos, 0);
1227 if (r != data_size) {
1228 archive_set_error(&a->archive,
1229 (r < 0)?errno:ARCHIVE_ERRNO_MISC,
1230 "Failed to read resource fork");
1231 return (ARCHIVE_WARN);
1233 if (a->compressed_buffer[0] == 0xff) {
1234 bytes_to_write = data_size -1;
1235 b = a->compressed_buffer + 1;
1237 uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1240 zr = uncompress((Bytef *)a->uncompressed_buffer,
1241 &dest_len, a->compressed_buffer, data_size);
1243 archive_set_error(&a->archive,
1245 "Failed to decompress resource fork");
1246 return (ARCHIVE_WARN);
1248 bytes_to_write = dest_len;
1249 b = (unsigned char *)a->uncompressed_buffer;
1252 bytes_written = write(a->fd, b, bytes_to_write);
1253 if (bytes_written < 0) {
1254 archive_set_error(&a->archive, errno,
1256 return (ARCHIVE_WARN);
1258 bytes_to_write -= bytes_written;
1260 } while (bytes_to_write > 0);
1262 r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1264 archive_set_error(&a->archive, errno,
1265 "Failed to remove resource fork");
1266 return (ARCHIVE_WARN);
1268 return (ARCHIVE_OK);
1272 hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1275 unsigned char *buffer_compressed;
1276 size_t bytes_compressed;
1280 ret = hfs_reset_compressor(a);
1281 if (ret != ARCHIVE_OK)
1284 if (a->compressed_buffer == NULL) {
1287 block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
1288 + compressBound(MAX_DECMPFS_BLOCK_SIZE);
1289 a->compressed_buffer = malloc(block_size);
1290 if (a->compressed_buffer == NULL) {
1291 archive_set_error(&a->archive, ENOMEM,
1292 "Can't allocate memory for Resource Fork");
1293 return (ARCHIVE_FATAL);
1295 a->compressed_buffer_size = block_size;
1296 a->compressed_buffer_remaining = block_size;
1299 buffer_compressed = a->compressed_buffer +
1300 a->compressed_buffer_size - a->compressed_buffer_remaining;
1301 a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
1302 a->stream.avail_in = size;
1303 a->stream.next_out = buffer_compressed;
1304 a->stream.avail_out = a->compressed_buffer_remaining;
1306 ret = deflate(&a->stream, Z_FINISH);
1312 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1313 "Failed to compress data");
1314 return (ARCHIVE_FAILED);
1316 } while (ret == Z_OK);
1317 bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1320 * If the compressed size is larger than the original size,
1321 * throw away compressed data, use uncompressed data instead.
1323 if (bytes_compressed > size) {
1324 buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1325 memcpy(buffer_compressed + 1, buff, size);
1326 bytes_compressed = size + 1;
1328 a->compressed_buffer_remaining -= bytes_compressed;
1331 * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
1332 * and the block count in the file is only one, store compressed
1333 * data to decmpfs xattr instead of the resource fork.
1335 if (a->decmpfs_block_count == 1 &&
1336 (a->decmpfs_attr_size + bytes_compressed)
1337 <= MAX_DECMPFS_XATTR_SIZE) {
1338 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1340 memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
1341 buffer_compressed, bytes_compressed);
1342 a->decmpfs_attr_size += bytes_compressed;
1343 a->compressed_buffer_remaining = a->compressed_buffer_size;
1345 * Finish HFS+ Compression.
1346 * - Write the decmpfs xattr.
1347 * - Set the UF_COMPRESSED file flag.
1349 ret = hfs_write_decmpfs(a);
1350 if (ret == ARCHIVE_OK)
1351 ret = hfs_set_compressed_fflag(a);
1355 /* Update block info. */
1356 archive_le32enc(a->decmpfs_block_info++,
1357 a->compressed_rsrc_position_v - RSRC_H_SIZE);
1358 archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
1359 a->compressed_rsrc_position_v += bytes_compressed;
1362 * Write the compressed data to the resource fork.
1364 bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
1365 while (bytes_used >= COMPRESSED_W_SIZE) {
1366 ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
1367 if (ret != ARCHIVE_OK)
1369 bytes_used -= COMPRESSED_W_SIZE;
1370 if (bytes_used > COMPRESSED_W_SIZE)
1371 memmove(a->compressed_buffer,
1372 a->compressed_buffer + COMPRESSED_W_SIZE,
1375 memcpy(a->compressed_buffer,
1376 a->compressed_buffer + COMPRESSED_W_SIZE,
1379 a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1382 * If the current block is the last block, write the remaining
1383 * compressed data and the resource fork footer.
1385 if (a->file_remaining_bytes == 0) {
1389 /* Append the resource footer. */
1390 rsrc_size = hfs_set_resource_fork_footer(
1391 a->compressed_buffer + bytes_used,
1392 a->compressed_buffer_remaining);
1393 ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
1394 a->compressed_buffer_remaining = a->compressed_buffer_size;
1396 /* If the compressed size is not enough smaller than
1397 * the uncompressed size. cancel HFS+ compression.
1398 * TODO: study a behavior of ditto utility and improve
1399 * the condition to fall back into no HFS+ compression. */
1400 bk = HFS_BLOCKS(a->compressed_rsrc_position);
1402 if (bk > HFS_BLOCKS(a->filesize))
1403 return hfs_decompress(a);
1405 * Write the resourcefork header.
1407 if (ret == ARCHIVE_OK)
1408 ret = hfs_write_resource_fork_header(a);
1410 * Finish HFS+ Compression.
1411 * - Write the decmpfs xattr.
1412 * - Set the UF_COMPRESSED file flag.
1414 if (ret == ARCHIVE_OK)
1415 ret = hfs_write_decmpfs(a);
1416 if (ret == ARCHIVE_OK)
1417 ret = hfs_set_compressed_fflag(a);
1423 hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1426 const char *buffer_to_write;
1427 size_t bytes_to_write;
1430 if (a->decmpfs_block_count == (unsigned)-1) {
1433 unsigned int block_count;
1435 if (a->decmpfs_header_p == NULL) {
1436 new_block = malloc(MAX_DECMPFS_XATTR_SIZE
1437 + sizeof(uint32_t));
1438 if (new_block == NULL) {
1439 archive_set_error(&a->archive, ENOMEM,
1440 "Can't allocate memory for decmpfs");
1441 return (ARCHIVE_FATAL);
1443 a->decmpfs_header_p = new_block;
1445 a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1446 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1448 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1450 archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1453 /* Calculate a block count of the file. */
1455 (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1456 MAX_DECMPFS_BLOCK_SIZE;
1458 * Allocate buffer for resource fork.
1459 * Set up related pointers;
1462 RSRC_H_SIZE + /* header */
1463 4 + /* Block count */
1464 (block_count * sizeof(uint32_t) * 2) +
1465 RSRC_F_SIZE; /* footer */
1466 if (new_size > a->resource_fork_allocated_size) {
1467 new_block = realloc(a->resource_fork, new_size);
1468 if (new_block == NULL) {
1469 archive_set_error(&a->archive, ENOMEM,
1470 "Can't allocate memory for ResourceFork");
1471 return (ARCHIVE_FATAL);
1473 a->resource_fork_allocated_size = new_size;
1474 a->resource_fork = new_block;
1477 /* Allocate uncompressed buffer */
1478 if (a->uncompressed_buffer == NULL) {
1479 new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
1480 if (new_block == NULL) {
1481 archive_set_error(&a->archive, ENOMEM,
1482 "Can't allocate memory for decmpfs");
1483 return (ARCHIVE_FATAL);
1485 a->uncompressed_buffer = new_block;
1487 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1488 a->file_remaining_bytes = a->filesize;
1489 a->compressed_buffer_remaining = a->compressed_buffer_size;
1492 * Set up a resource fork.
1494 a->rsrc_xattr_options = XATTR_CREATE;
1495 /* Get the position where we are going to set a bunch
1497 a->decmpfs_block_info =
1498 (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1499 /* Set the block count to the resource fork. */
1500 archive_le32enc(a->decmpfs_block_info++, block_count);
1501 /* Get the position where we are going to set compressed
1503 a->compressed_rsrc_position =
1504 RSRC_H_SIZE + 4 + (block_count * 8);
1505 a->compressed_rsrc_position_v = a->compressed_rsrc_position;
1506 a->decmpfs_block_count = block_count;
1509 /* Ignore redundant bytes. */
1510 if (a->file_remaining_bytes == 0)
1511 return ((ssize_t)size);
1513 /* Do not overrun a block size. */
1514 if (size > a->block_remaining_bytes)
1515 bytes_to_write = a->block_remaining_bytes;
1517 bytes_to_write = size;
1518 /* Do not overrun the file size. */
1519 if (bytes_to_write > a->file_remaining_bytes)
1520 bytes_to_write = a->file_remaining_bytes;
1522 /* For efficiency, if a copy length is full of the uncompressed
1523 * buffer size, do not copy writing data to it. */
1524 if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
1525 buffer_to_write = buff;
1527 memcpy(a->uncompressed_buffer +
1528 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
1529 buff, bytes_to_write);
1530 buffer_to_write = a->uncompressed_buffer;
1532 a->block_remaining_bytes -= bytes_to_write;
1533 a->file_remaining_bytes -= bytes_to_write;
1535 if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
1536 ret = hfs_drive_compressor(a, buffer_to_write,
1537 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
1540 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1542 /* Ignore redundant bytes. */
1543 if (a->file_remaining_bytes == 0)
1544 return ((ssize_t)size);
1545 return (bytes_to_write);
1549 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1552 uint64_t start_size = size;
1553 ssize_t bytes_written = 0;
1554 ssize_t bytes_to_write;
1557 return (ARCHIVE_OK);
1559 if (a->filesize == 0 || a->fd < 0) {
1560 archive_set_error(&a->archive, 0,
1561 "Attempt to write to an empty file");
1562 return (ARCHIVE_WARN);
1565 /* If this write would run beyond the file size, truncate it. */
1566 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
1567 start_size = size = (size_t)(a->filesize - a->offset);
1569 /* Write the data. */
1571 bytes_to_write = size;
1572 /* Seek if necessary to the specified offset. */
1573 if (a->offset < a->fd_offset) {
1574 /* Can't support backward move. */
1575 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1577 return (ARCHIVE_FATAL);
1578 } else if (a->offset > a->fd_offset) {
1579 int64_t skip = a->offset - a->fd_offset;
1580 char nullblock[1024];
1582 memset(nullblock, 0, sizeof(nullblock));
1584 if (skip > (int64_t)sizeof(nullblock))
1585 bytes_written = hfs_write_decmpfs_block(
1586 a, nullblock, sizeof(nullblock));
1588 bytes_written = hfs_write_decmpfs_block(
1589 a, nullblock, skip);
1590 if (bytes_written < 0) {
1591 archive_set_error(&a->archive, errno,
1593 return (ARCHIVE_WARN);
1595 skip -= bytes_written;
1598 a->fd_offset = a->offset;
1601 hfs_write_decmpfs_block(a, buff, bytes_to_write);
1602 if (bytes_written < 0)
1603 return (bytes_written);
1604 buff += bytes_written;
1605 size -= bytes_written;
1606 a->total_bytes_written += bytes_written;
1607 a->offset += bytes_written;
1608 a->fd_offset = a->offset;
1610 return (start_size - size);
1614 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1617 return (write_data_block(a, buff, size));
1622 _archive_write_disk_data_block(struct archive *_a,
1623 const void *buff, size_t size, int64_t offset)
1625 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1628 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1629 ARCHIVE_STATE_DATA, "archive_write_data_block");
1632 if (a->todo & TODO_HFS_COMPRESSION)
1633 r = hfs_write_data_block(a, buff, size);
1635 r = write_data_block(a, buff, size);
1638 if ((size_t)r < size) {
1639 archive_set_error(&a->archive, 0,
1640 "Too much data: Truncating file at %ju bytes",
1641 (uintmax_t)a->filesize);
1642 return (ARCHIVE_WARN);
1644 #if ARCHIVE_VERSION_NUMBER < 3999000
1645 return (ARCHIVE_OK);
1652 _archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1654 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1656 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1657 ARCHIVE_STATE_DATA, "archive_write_data");
1659 if (a->todo & TODO_HFS_COMPRESSION)
1660 return (hfs_write_data_block(a, buff, size));
1661 return (write_data_block(a, buff, size));
1665 _archive_write_disk_finish_entry(struct archive *_a)
1667 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1668 int ret = ARCHIVE_OK;
1670 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1671 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1672 "archive_write_finish_entry");
1673 if (a->archive.state & ARCHIVE_STATE_HEADER)
1674 return (ARCHIVE_OK);
1675 archive_clear_error(&a->archive);
1677 /* Pad or truncate file to the right size. */
1679 /* There's no file. */
1680 } else if (a->filesize < 0) {
1681 /* File size is unknown, so we can't set the size. */
1682 } else if (a->fd_offset == a->filesize) {
1683 /* Last write ended at exactly the filesize; we're done. */
1684 /* Hopefully, this is the common case. */
1685 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
1686 } else if (a->todo & TODO_HFS_COMPRESSION) {
1690 if (a->file_remaining_bytes)
1691 memset(null_d, 0, sizeof(null_d));
1692 while (a->file_remaining_bytes) {
1693 if (a->file_remaining_bytes > sizeof(null_d))
1694 r = hfs_write_data_block(
1695 a, null_d, sizeof(null_d));
1697 r = hfs_write_data_block(
1698 a, null_d, a->file_remaining_bytes);
1705 if (ftruncate(a->fd, a->filesize) == -1 &&
1707 archive_set_error(&a->archive, errno,
1708 "File size could not be restored");
1709 return (ARCHIVE_FAILED);
1713 * Not all platforms implement the XSI option to
1714 * extend files via ftruncate. Stat() the file again
1715 * to see what happened.
1718 if ((ret = lazy_stat(a)) != ARCHIVE_OK)
1720 /* We can use lseek()/write() to extend the file if
1721 * ftruncate didn't work or isn't available. */
1722 if (a->st.st_size < a->filesize) {
1723 const char nul = '\0';
1724 if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
1725 archive_set_error(&a->archive, errno,
1727 return (ARCHIVE_FATAL);
1729 if (write(a->fd, &nul, 1) < 0) {
1730 archive_set_error(&a->archive, errno,
1731 "Write to restore size failed");
1732 return (ARCHIVE_FATAL);
1738 /* Restore metadata. */
1741 * This is specific to Mac OS X.
1742 * If the current file is an AppleDouble file, it should be
1743 * linked with the data fork file and remove it.
1745 if (a->todo & TODO_APPLEDOUBLE) {
1746 int r2 = fixup_appledouble(a, a->name);
1747 if (r2 == ARCHIVE_EOF) {
1748 /* The current file has been successfully linked
1749 * with the data fork file and removed. So there
1750 * is nothing to do on the current file. */
1751 goto finish_metadata;
1753 if (r2 < ret) ret = r2;
1757 * Look up the "real" UID only if we're going to need it.
1758 * TODO: the TODO_SGID condition can be dropped here, can't it?
1760 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
1761 a->uid = archive_write_disk_uid(&a->archive,
1762 archive_entry_uname(a->entry),
1763 archive_entry_uid(a->entry));
1765 /* Look up the "real" GID only if we're going to need it. */
1766 /* TODO: the TODO_SUID condition can be dropped here, can't it? */
1767 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
1768 a->gid = archive_write_disk_gid(&a->archive,
1769 archive_entry_gname(a->entry),
1770 archive_entry_gid(a->entry));
1774 * Restore ownership before set_mode tries to restore suid/sgid
1775 * bits. If we set the owner, we know what it is and can skip
1776 * a stat() call to examine the ownership of the file on disk.
1778 if (a->todo & TODO_OWNER) {
1779 int r2 = set_ownership(a);
1780 if (r2 < ret) ret = r2;
1784 * set_mode must precede ACLs on systems such as Solaris and
1785 * FreeBSD where setting the mode implicitly clears extended ACLs
1787 if (a->todo & TODO_MODE) {
1788 int r2 = set_mode(a, a->mode);
1789 if (r2 < ret) ret = r2;
1793 * Security-related extended attributes (such as
1794 * security.capability on Linux) have to be restored last,
1795 * since they're implicitly removed by other file changes.
1797 if (a->todo & TODO_XATTR) {
1798 int r2 = set_xattrs(a);
1799 if (r2 < ret) ret = r2;
1803 * Some flags prevent file modification; they must be restored after
1804 * file contents are written.
1806 if (a->todo & TODO_FFLAGS) {
1807 int r2 = set_fflags(a);
1808 if (r2 < ret) ret = r2;
1812 * Time must follow most other metadata;
1813 * otherwise atime will get changed.
1815 if (a->todo & TODO_TIMES) {
1816 int r2 = set_times_from_entry(a);
1817 if (r2 < ret) ret = r2;
1821 * Mac extended metadata includes ACLs.
1823 if (a->todo & TODO_MAC_METADATA) {
1824 const void *metadata;
1825 size_t metadata_size;
1826 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
1827 if (metadata != NULL && metadata_size > 0) {
1828 int r2 = set_mac_metadata(a, archive_entry_pathname(
1829 a->entry), metadata, metadata_size);
1830 if (r2 < ret) ret = r2;
1835 * ACLs must be restored after timestamps because there are
1836 * ACLs that prevent attribute changes (including time).
1838 if (a->todo & TODO_ACLS) {
1840 r2 = archive_write_disk_set_acls(&a->archive, a->fd,
1841 archive_entry_pathname(a->entry),
1842 archive_entry_acl(a->entry),
1843 archive_entry_mode(a->entry));
1844 if (r2 < ret) ret = r2;
1848 /* If there's an fd, we can close it now. */
1853 if (rename(a->tmpname, a->name) == -1) {
1854 archive_set_error(&a->archive, errno,
1855 "Failed to rename temporary file");
1856 ret = ARCHIVE_FAILED;
1862 /* If there's an entry, we can release it now. */
1863 archive_entry_free(a->entry);
1865 a->archive.state = ARCHIVE_STATE_HEADER;
1870 archive_write_disk_set_group_lookup(struct archive *_a,
1872 la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1873 void (*cleanup_gid)(void *private))
1875 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1876 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1877 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
1879 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1880 (a->cleanup_gid)(a->lookup_gid_data);
1882 a->lookup_gid = lookup_gid;
1883 a->cleanup_gid = cleanup_gid;
1884 a->lookup_gid_data = private_data;
1885 return (ARCHIVE_OK);
1889 archive_write_disk_set_user_lookup(struct archive *_a,
1891 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1892 void (*cleanup_uid)(void *private))
1894 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1895 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1896 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
1898 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1899 (a->cleanup_uid)(a->lookup_uid_data);
1901 a->lookup_uid = lookup_uid;
1902 a->cleanup_uid = cleanup_uid;
1903 a->lookup_uid_data = private_data;
1904 return (ARCHIVE_OK);
1908 archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1910 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1911 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1912 ARCHIVE_STATE_ANY, "archive_write_disk_gid");
1914 return (a->lookup_gid)(a->lookup_gid_data, name, id);
1919 archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1921 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1922 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1923 ARCHIVE_STATE_ANY, "archive_write_disk_uid");
1925 return (a->lookup_uid)(a->lookup_uid_data, name, id);
1930 * Create a new archive_write_disk object and initialize it with global state.
1933 archive_write_disk_new(void)
1935 struct archive_write_disk *a;
1937 a = (struct archive_write_disk *)calloc(1, sizeof(*a));
1940 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
1941 /* We're ready to write a header immediately. */
1942 a->archive.state = ARCHIVE_STATE_HEADER;
1943 a->archive.vtable = archive_write_disk_vtable();
1944 a->start_time = time(NULL);
1945 /* Query and restore the umask. */
1946 umask(a->user_umask = umask(0));
1948 a->user_uid = geteuid();
1949 #endif /* HAVE_GETEUID */
1950 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
1955 a->decmpfs_compression_level = 5;
1957 return (&a->archive);
1962 * If pathname is longer than PATH_MAX, chdir to a suitable
1963 * intermediate dir and edit the path down to a shorter suffix. Note
1964 * that this routine never returns an error; if the chdir() attempt
1965 * fails for any reason, we just go ahead with the long pathname. The
1966 * object creation is likely to fail, but any error will get handled
1969 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
1971 edit_deep_directories(struct archive_write_disk *a)
1974 char *tail = a->name;
1976 /* If path is short, avoid the open() below. */
1977 if (strlen(tail) < PATH_MAX)
1980 /* Try to record our starting dir. */
1981 a->restore_pwd = la_opendirat(AT_FDCWD, ".");
1982 __archive_ensure_cloexec_flag(a->restore_pwd);
1983 if (a->restore_pwd < 0)
1986 /* As long as the path is too long... */
1987 while (strlen(tail) >= PATH_MAX) {
1988 /* Locate a dir prefix shorter than PATH_MAX. */
1989 tail += PATH_MAX - 8;
1990 while (tail > a->name && *tail != '/')
1992 /* Exit if we find a too-long path component. */
1993 if (tail <= a->name)
1995 /* Create the intermediate dir and chdir to it. */
1996 *tail = '\0'; /* Terminate dir portion */
1997 ret = create_dir(a, a->name);
1998 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
1999 ret = ARCHIVE_FAILED;
2000 *tail = '/'; /* Restore the / we removed. */
2001 if (ret != ARCHIVE_OK)
2004 /* The chdir() succeeded; we've now shortened the path. */
2012 * The main restore function.
2015 restore_entry(struct archive_write_disk *a)
2017 int ret = ARCHIVE_OK, en;
2019 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
2021 * TODO: Fix this. Apparently, there are platforms
2022 * that still allow root to hose the entire filesystem
2023 * by unlinking a dir. The S_ISDIR() test above
2024 * prevents us from using unlink() here if the new
2025 * object is a dir, but that doesn't mean the old
2026 * object isn't a dir.
2028 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2029 (void)clear_nochange_fflags(a);
2030 if (unlink(a->name) == 0) {
2031 /* We removed it, reset cached stat. */
2033 } else if (errno == ENOENT) {
2034 /* File didn't exist, that's just as good. */
2035 } else if (rmdir(a->name) == 0) {
2036 /* It was a dir, but now it's gone. */
2039 /* We tried, but couldn't get rid of it. */
2040 archive_set_error(&a->archive, errno,
2041 "Could not unlink");
2042 return(ARCHIVE_FAILED);
2046 /* Try creating it first; if this fails, we'll try to recover. */
2047 en = create_filesystem_object(a);
2049 if ((en == ENOTDIR || en == ENOENT)
2050 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
2051 /* If the parent dir doesn't exist, try creating it. */
2052 create_parent_dir(a, a->name);
2053 /* Now try to create the object again. */
2054 en = create_filesystem_object(a);
2057 if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
2058 archive_set_error(&a->archive, en,
2059 "Hard-link target '%s' does not exist.",
2060 archive_entry_hardlink(a->entry));
2061 return (ARCHIVE_FAILED);
2064 if ((en == EISDIR || en == EEXIST)
2065 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2066 /* If we're not overwriting, we're done. */
2067 if (S_ISDIR(a->mode)) {
2068 /* Don't overwrite any settings on existing directories. */
2071 archive_entry_unset_size(a->entry);
2072 return (ARCHIVE_OK);
2076 * Some platforms return EISDIR if you call
2077 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
2078 * return EEXIST. POSIX is ambiguous, requiring EISDIR
2079 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
2080 * on an existing item.
2083 /* A dir is in the way of a non-dir, rmdir it. */
2084 if (rmdir(a->name) != 0) {
2085 archive_set_error(&a->archive, errno,
2086 "Can't remove already-existing dir");
2087 return (ARCHIVE_FAILED);
2091 en = create_filesystem_object(a);
2092 } else if (en == EEXIST) {
2094 * We know something is in the way, but we don't know what;
2095 * we need to find out before we go any further.
2099 * The SECURE_SYMLINKS logic has already removed a
2100 * symlink to a dir if the client wants that. So
2101 * follow the symlink if we're creating a dir.
2103 if (S_ISDIR(a->mode))
2104 r = la_stat(a->name, &a->st);
2106 * If it's not a dir (or it's a broken symlink),
2107 * then don't follow it.
2109 if (r != 0 || !S_ISDIR(a->mode))
2110 r = lstat(a->name, &a->st);
2112 archive_set_error(&a->archive, errno,
2113 "Can't stat existing object");
2114 return (ARCHIVE_FAILED);
2118 * NO_OVERWRITE_NEWER doesn't apply to directories.
2120 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
2121 && !S_ISDIR(a->st.st_mode)) {
2122 if (!older(&(a->st), a->entry)) {
2123 archive_entry_unset_size(a->entry);
2124 return (ARCHIVE_OK);
2128 /* If it's our archive, we're done. */
2129 if (a->skip_file_set &&
2130 a->st.st_dev == (dev_t)a->skip_file_dev &&
2131 a->st.st_ino == (ino_t)a->skip_file_ino) {
2132 archive_set_error(&a->archive, 0,
2133 "Refusing to overwrite archive");
2134 return (ARCHIVE_FAILED);
2137 if (!S_ISDIR(a->st.st_mode)) {
2138 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2139 (void)clear_nochange_fflags(a);
2141 if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) &&
2142 S_ISREG(a->st.st_mode)) {
2143 /* Use a temporary file to extract */
2144 if ((a->fd = la_mktemp(a)) == -1) {
2145 archive_set_error(&a->archive, errno,
2146 "Can't create temporary file");
2147 return ARCHIVE_FAILED;
2152 /* A non-dir is in the way, unlink it. */
2153 if (unlink(a->name) != 0) {
2154 archive_set_error(&a->archive, errno,
2155 "Can't unlink already-existing "
2157 return (ARCHIVE_FAILED);
2161 en = create_filesystem_object(a);
2163 } else if (!S_ISDIR(a->mode)) {
2164 /* A dir is in the way of a non-dir, rmdir it. */
2165 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2166 (void)clear_nochange_fflags(a);
2167 if (rmdir(a->name) != 0) {
2168 archive_set_error(&a->archive, errno,
2169 "Can't replace existing directory with non-directory");
2170 return (ARCHIVE_FAILED);
2173 en = create_filesystem_object(a);
2176 * There's a dir in the way of a dir. Don't
2177 * waste time with rmdir()/mkdir(), just fix
2178 * up the permissions on the existing dir.
2179 * Note that we don't change perms on existing
2180 * dirs unless _EXTRACT_PERM is specified.
2182 if ((a->mode != a->st.st_mode)
2183 && (a->todo & TODO_MODE_FORCE))
2184 a->deferred |= (a->todo & TODO_MODE);
2185 /* Ownership doesn't need deferred fixup. */
2186 en = 0; /* Forget the EEXIST. */
2191 /* Everything failed; give up here. */
2192 if ((&a->archive)->error == NULL)
2193 archive_set_error(&a->archive, en, "Can't create '%s'",
2195 return (ARCHIVE_FAILED);
2198 a->pst = NULL; /* Cached stat data no longer valid. */
2203 * Returns 0 if creation succeeds, or else returns errno value from
2204 * the failed system call. Note: This function should only ever perform
2205 * a single system call.
2208 create_filesystem_object(struct archive_write_disk *a)
2210 /* Create the entry. */
2211 const char *linkname;
2212 mode_t final_mode, mode;
2214 /* these for check_symlinks_fsobj */
2215 char *linkname_copy; /* non-const copy of linkname */
2217 struct archive_string error_string;
2220 /* We identify hard/symlinks according to the link names. */
2221 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
2222 linkname = archive_entry_hardlink(a->entry);
2223 if (linkname != NULL) {
2227 archive_string_init(&error_string);
2228 linkname_copy = strdup(linkname);
2229 if (linkname_copy == NULL) {
2233 * TODO: consider using the cleaned-up path as the link
2236 r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2237 &error_string, a->flags);
2238 if (r != ARCHIVE_OK) {
2239 archive_set_error(&a->archive, error_number, "%s",
2241 free(linkname_copy);
2242 archive_string_free(&error_string);
2244 * EPERM is more appropriate than error_number for our
2249 r = check_symlinks_fsobj(linkname_copy, &error_number,
2250 &error_string, a->flags);
2251 if (r != ARCHIVE_OK) {
2252 archive_set_error(&a->archive, error_number, "%s",
2254 free(linkname_copy);
2255 archive_string_free(&error_string);
2257 * EPERM is more appropriate than error_number for our
2262 free(linkname_copy);
2263 archive_string_free(&error_string);
2265 * Unlinking and linking here is really not atomic,
2266 * but doing it right, would require us to construct
2267 * an mktemplink() function, and then use rename(2).
2269 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2271 r = link(linkname, a->name) ? errno : 0;
2273 * New cpio and pax formats allow hardlink entries
2274 * to carry data, so we may have to open the file
2275 * for hardlink entries.
2277 * If the hardlink was successfully created and
2278 * the archive doesn't have carry data for it,
2279 * consider it to be non-authoritative for meta data.
2280 * This is consistent with GNU tar and BSD pax.
2281 * If the hardlink does carry data, let the last
2282 * archive entry decide ownership.
2284 if (r == 0 && a->filesize <= 0) {
2287 } else if (r == 0 && a->filesize > 0) {
2289 r = lstat(a->name, &st);
2291 r = la_stat(a->name, &st);
2295 else if ((st.st_mode & AE_IFMT) == AE_IFREG) {
2296 a->fd = open(a->name, O_WRONLY | O_TRUNC |
2297 O_BINARY | O_CLOEXEC | O_NOFOLLOW);
2298 __archive_ensure_cloexec_flag(a->fd);
2306 linkname = archive_entry_symlink(a->entry);
2307 if (linkname != NULL) {
2310 * Unlinking and linking here is really not atomic,
2311 * but doing it right, would require us to construct
2312 * an mktempsymlink() function, and then use rename(2).
2314 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2316 return symlink(linkname, a->name) ? errno : 0;
2323 * The remaining system calls all set permissions, so let's
2324 * try to take advantage of that to avoid an extra chmod()
2325 * call. (Recall that umask is set to zero right now!)
2328 /* Mode we want for the final restored object (w/o file type bits). */
2329 final_mode = a->mode & 07777;
2331 * The mode that will actually be restored in this step. Note
2332 * that SUID, SGID, etc, require additional work to ensure
2333 * security, so we never restore them at this point.
2335 mode = final_mode & 0777 & ~a->user_umask;
2337 switch (a->mode & AE_IFMT) {
2339 /* POSIX requires that we fall through here. */
2343 a->fd = open(a->name,
2344 O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2345 __archive_ensure_cloexec_flag(a->fd);
2350 /* Note: we use AE_IFCHR for the case label, and
2351 * S_IFCHR for the mknod() call. This is correct. */
2352 r = mknod(a->name, mode | S_IFCHR,
2353 archive_entry_rdev(a->entry));
2356 /* TODO: Find a better way to warn about our inability
2357 * to restore a char device node. */
2359 #endif /* HAVE_MKNOD */
2362 r = mknod(a->name, mode | S_IFBLK,
2363 archive_entry_rdev(a->entry));
2366 /* TODO: Find a better way to warn about our inability
2367 * to restore a block device node. */
2369 #endif /* HAVE_MKNOD */
2371 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2372 r = mkdir(a->name, mode);
2374 /* Defer setting dir times. */
2375 a->deferred |= (a->todo & TODO_TIMES);
2376 a->todo &= ~TODO_TIMES;
2377 /* Never use an immediate chmod(). */
2378 /* We can't avoid the chmod() entirely if EXTRACT_PERM
2379 * because of SysV SGID inheritance. */
2380 if ((mode != final_mode)
2381 || (a->flags & ARCHIVE_EXTRACT_PERM))
2382 a->deferred |= (a->todo & TODO_MODE);
2383 a->todo &= ~TODO_MODE;
2388 r = mkfifo(a->name, mode);
2391 /* TODO: Find a better way to warn about our inability
2392 * to restore a fifo. */
2394 #endif /* HAVE_MKFIFO */
2397 /* All the system calls above set errno on failure. */
2401 /* If we managed to set the final mode, we've avoided a chmod(). */
2402 if (mode == final_mode)
2403 a->todo &= ~TODO_MODE;
2408 * Cleanup function for archive_extract. Mostly, this involves processing
2409 * the fixup list, which is used to address a number of problems:
2410 * * Dir permissions might prevent us from restoring a file in that
2411 * dir, so we restore the dir with minimum 0700 permissions first,
2412 * then correct the mode at the end.
2413 * * Similarly, the act of restoring a file touches the directory
2414 * and changes the timestamp on the dir, so we have to touch-up dir
2415 * timestamps at the end as well.
2416 * * Some file flags can interfere with the restore by, for example,
2417 * preventing the creation of hardlinks to those files.
2418 * * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2420 * Note that tar/cpio do not require that archives be in a particular
2421 * order; there is no way to know when the last file has been restored
2422 * within a directory, so there's no way to optimize the memory usage
2423 * here by fixing up the directory any earlier than the
2426 * XXX TODO: Directory ACLs should be restored here, for the same
2427 * reason we set directory perms here. XXX
2430 _archive_write_disk_close(struct archive *_a)
2432 struct archive_write_disk *a = (struct archive_write_disk *)_a;
2433 struct fixup_entry *next, *p;
2436 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2437 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2438 "archive_write_disk_close");
2439 ret = _archive_write_disk_finish_entry(&a->archive);
2441 /* Sort dir list so directories are fixed up in depth-first order. */
2442 p = sort_dir_list(a->fixup_list);
2446 a->pst = NULL; /* Mark stat cache as out-of-date. */
2448 (TODO_TIMES | TODO_MODE_BASE | TODO_ACLS | TODO_FFLAGS)) {
2450 O_WRONLY | O_BINARY | O_NOFOLLOW | O_CLOEXEC);
2452 if (p->fixup & TODO_TIMES) {
2453 set_times(a, fd, p->mode, p->name,
2454 p->atime, p->atime_nanos,
2455 p->birthtime, p->birthtime_nanos,
2456 p->mtime, p->mtime_nanos,
2457 p->ctime, p->ctime_nanos);
2459 if (p->fixup & TODO_MODE_BASE) {
2462 fchmod(fd, p->mode);
2465 chmod(p->name, p->mode);
2467 if (p->fixup & TODO_ACLS)
2468 archive_write_disk_set_acls(&a->archive, fd,
2469 p->name, &p->acl, p->mode);
2470 if (p->fixup & TODO_FFLAGS)
2471 set_fflags_platform(a, fd, p->name,
2472 p->mode, p->fflags_set, 0);
2473 if (p->fixup & TODO_MAC_METADATA)
2474 set_mac_metadata(a, p->name, p->mac_metadata,
2475 p->mac_metadata_size);
2477 archive_acl_clear(&p->acl);
2478 free(p->mac_metadata);
2485 a->fixup_list = NULL;
2490 _archive_write_disk_free(struct archive *_a)
2492 struct archive_write_disk *a;
2495 return (ARCHIVE_OK);
2496 archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2497 ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2498 a = (struct archive_write_disk *)_a;
2499 ret = _archive_write_disk_close(&a->archive);
2500 archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2501 archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2502 archive_entry_free(a->entry);
2503 archive_string_free(&a->_name_data);
2504 archive_string_free(&a->_tmpname_data);
2505 archive_string_free(&a->archive.error_string);
2506 archive_string_free(&a->path_safe);
2507 a->archive.magic = 0;
2508 __archive_clean(&a->archive);
2509 free(a->decmpfs_header_p);
2510 free(a->resource_fork);
2511 free(a->compressed_buffer);
2512 free(a->uncompressed_buffer);
2513 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2514 && defined(HAVE_ZLIB_H)
2515 if (a->stream_valid) {
2516 switch (deflateEnd(&a->stream)) {
2520 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2521 "Failed to clean up compressor");
2522 ret = ARCHIVE_FATAL;
2532 * Simple O(n log n) merge sort to order the fixup list. In
2533 * particular, we want to restore dir timestamps depth-first.
2535 static struct fixup_entry *
2536 sort_dir_list(struct fixup_entry *p)
2538 struct fixup_entry *a, *b, *t;
2542 /* A one-item list is already sorted. */
2543 if (p->next == NULL)
2546 /* Step 1: split the list. */
2550 /* Step a twice, t once. */
2556 /* Now, t is at the mid-point, so break the list here. */
2561 /* Step 2: Recursively sort the two sub-lists. */
2562 a = sort_dir_list(a);
2563 b = sort_dir_list(b);
2565 /* Step 3: Merge the returned lists. */
2566 /* Pick the first element for the merged list. */
2567 if (strcmp(a->name, b->name) > 0) {
2575 /* Always put the later element on the list first. */
2576 while (a != NULL && b != NULL) {
2577 if (strcmp(a->name, b->name) > 0) {
2587 /* Only one list is non-empty, so just splice it on. */
2597 * Returns a new, initialized fixup entry.
2599 * TODO: Reduce the memory requirements for this list by using a tree
2600 * structure rather than a simple list of names.
2602 static struct fixup_entry *
2603 new_fixup(struct archive_write_disk *a, const char *pathname)
2605 struct fixup_entry *fe;
2607 fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2609 archive_set_error(&a->archive, ENOMEM,
2610 "Can't allocate memory for a fixup");
2613 fe->next = a->fixup_list;
2616 fe->name = strdup(pathname);
2621 * Returns a fixup structure for the current entry.
2623 static struct fixup_entry *
2624 current_fixup(struct archive_write_disk *a, const char *pathname)
2626 if (a->current_fixup == NULL)
2627 a->current_fixup = new_fixup(a, pathname);
2628 return (a->current_fixup);
2631 /* Error helper for new *_fsobj functions */
2633 fsobj_error(int *a_eno, struct archive_string *a_estr,
2634 int err, const char *errstr, const char *path)
2639 archive_string_sprintf(a_estr, "%s%s", errstr, path);
2643 * TODO: Someday, integrate this with the deep dir support; they both
2644 * scan the path and both can be optimized by comparing against other
2648 * Checks the given path to see if any elements along it are symlinks. Returns
2649 * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2652 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2655 #if !defined(HAVE_LSTAT) && \
2656 !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT))
2657 /* Platform doesn't have lstat, so we can't look for symlinks. */
2658 (void)path; /* UNUSED */
2659 (void)error_number; /* UNUSED */
2660 (void)error_string; /* UNUSED */
2661 (void)flags; /* UNUSED */
2662 return (ARCHIVE_OK);
2664 int res = ARCHIVE_OK;
2672 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2676 /* Nothing to do here if name is empty */
2678 return (ARCHIVE_OK);
2681 * Guard against symlink tricks. Reject any archive entry whose
2682 * destination would be altered by a symlink.
2684 * Walk the filename in chunks separated by '/'. For each segment:
2685 * - if it doesn't exist, continue
2686 * - if it's symlink, abort or remove it
2687 * - if it's a directory and it's not the last chunk, cd into it
2689 * head points to the current (relative) path
2690 * tail points to the temporary \0 terminating the segment we're
2691 * currently examining
2692 * c holds what used to be in *tail
2693 * last is 1 if this is the last tail
2695 chdir_fd = la_opendirat(AT_FDCWD, ".");
2696 __archive_ensure_cloexec_flag(chdir_fd);
2698 fsobj_error(a_eno, a_estr, errno,
2699 "Could not open ", path);
2700 return (ARCHIVE_FATAL);
2705 /* TODO: reintroduce a safe cache here? */
2706 /* Skip the root directory if the path is absolute. */
2707 if(tail == path && tail[0] == '/')
2709 /* Keep going until we've checked the entire name.
2710 * head, tail, path all alias the same string, which is
2711 * temporarily zeroed at tail, so be careful restoring the
2712 * stashed (c=tail[0]) for error messages.
2713 * Exiting the loop with break is okay; continue is not.
2717 * Skip the separator we just consumed, plus any adjacent ones
2719 while (*tail == '/')
2721 /* Skip the next path element. */
2722 while (*tail != '\0' && *tail != '/')
2724 /* is this the last path component? */
2725 last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2726 /* temporarily truncate the string here */
2729 /* Check that we haven't hit a symlink. */
2730 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2731 r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW);
2733 r = lstat(head, &st);
2737 /* We've hit a dir that doesn't exist; stop now. */
2738 if (errno == ENOENT) {
2742 * Treat any other error as fatal - best to be
2744 * Note: This effectively disables deep
2745 * directory support when security checks are
2746 * enabled. Otherwise, very long pathnames that
2747 * trigger an error here could evade the
2749 * TODO: We could do better, but it would
2750 * probably require merging the symlink checks
2751 * with the deep-directory editing.
2753 fsobj_error(a_eno, a_estr, errno,
2754 "Could not stat ", path);
2755 res = ARCHIVE_FAILED;
2758 } else if (S_ISDIR(st.st_mode)) {
2760 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2761 fd = la_opendirat(chdir_fd, head);
2774 fsobj_error(a_eno, a_estr, errno,
2775 "Could not chdir ", path);
2776 res = (ARCHIVE_FATAL);
2779 /* Our view is now from inside this dir: */
2782 } else if (S_ISLNK(st.st_mode)) {
2785 * Last element is symlink; remove it
2786 * so we can overwrite it with the
2787 * item being extracted.
2789 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2790 r = unlinkat(chdir_fd, head, 0);
2796 fsobj_error(a_eno, a_estr, errno,
2797 "Could not remove symlink ",
2799 res = ARCHIVE_FAILED;
2803 * Even if we did remove it, a warning
2804 * is in order. The warning is silly,
2805 * though, if we're just replacing one
2806 * symlink with another symlink.
2810 * FIXME: not sure how important this is to
2814 if (!S_ISLNK(path)) {
2815 fsobj_error(a_eno, a_estr, 0,
2816 "Removing symlink ", path);
2819 /* Symlink gone. No more problem! */
2822 } else if (flags & ARCHIVE_EXTRACT_UNLINK) {
2823 /* User asked us to remove problems. */
2824 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2825 r = unlinkat(chdir_fd, head, 0);
2831 fsobj_error(a_eno, a_estr, 0,
2832 "Cannot remove intervening "
2834 res = ARCHIVE_FAILED;
2839 ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
2841 * We are not the last element and we want to
2842 * follow symlinks if they are a directory.
2844 * This is needed to extract hardlinks over
2847 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2848 r = fstatat(chdir_fd, head, &st, 0);
2850 r = la_stat(head, &st);
2854 if (errno == ENOENT) {
2857 fsobj_error(a_eno, a_estr,
2859 "Could not stat ", path);
2860 res = (ARCHIVE_FAILED);
2863 } else if (S_ISDIR(st.st_mode)) {
2864 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2865 fd = la_opendirat(chdir_fd, head);
2878 fsobj_error(a_eno, a_estr,
2880 "Could not chdir ", path);
2881 res = (ARCHIVE_FATAL);
2885 * Our view is now from inside
2891 fsobj_error(a_eno, a_estr, 0,
2892 "Cannot extract through "
2894 res = ARCHIVE_FAILED;
2899 fsobj_error(a_eno, a_estr, 0,
2900 "Cannot extract through symlink ", path);
2901 res = ARCHIVE_FAILED;
2905 /* be sure to always maintain this */
2907 if (tail[0] != '\0')
2908 tail++; /* Advance to the next segment. */
2910 /* Catches loop exits via break */
2912 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2913 /* If we operate with openat(), fstatat() and unlinkat() there was
2914 * no chdir(), so just close the fd */
2918 /* If we changed directory above, restore it here. */
2919 if (chdir_fd >= 0) {
2920 r = fchdir(chdir_fd);
2922 fsobj_error(a_eno, a_estr, errno,
2923 "chdir() failure", "");
2928 res = (ARCHIVE_FATAL);
2932 /* TODO: reintroduce a safe cache here? */
2938 * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
2939 * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
2942 check_symlinks(struct archive_write_disk *a)
2944 struct archive_string error_string;
2947 archive_string_init(&error_string);
2948 rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
2950 if (rc != ARCHIVE_OK) {
2951 archive_set_error(&a->archive, error_number, "%s",
2954 archive_string_free(&error_string);
2955 a->pst = NULL; /* to be safe */
2960 #if defined(__CYGWIN__)
2962 * 1. Convert a path separator from '\' to '/' .
2963 * We shouldn't check multibyte character directly because some
2964 * character-set have been using the '\' character for a part of
2965 * its multibyte character code.
2966 * 2. Replace unusable characters in Windows with underscore('_').
2967 * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
2970 cleanup_pathname_win(char *path)
2975 int mb, complete, utf8;
2980 utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
2981 for (p = path; *p != '\0'; p++) {
2984 /* If previous byte is smaller than 128,
2985 * this is not second byte of multibyte characters,
2986 * so we can replace '\' with '/'. */
2990 complete = 0;/* uncompleted. */
2991 } else if (*(unsigned char *)p > 127)
2995 /* Rewrite the path name if its next character is unusable. */
2996 if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
2997 *p == '<' || *p == '>' || *p == '|')
3004 * Convert path separator in wide-character.
3007 while (*p != '\0' && alen) {
3008 l = mbtowc(&wc, p, alen);
3009 if (l == (size_t)-1) {
3010 while (*p != '\0') {
3017 if (l == 1 && wc == L'\\')
3026 * Canonicalize the pathname. In particular, this strips duplicate
3027 * '/' characters, '.' elements, and trailing '/'. It also raises an
3028 * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
3029 * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
3030 * is set) if the path is absolute.
3033 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
3037 char separator = '\0';
3041 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3042 "Invalid empty ", "pathname");
3043 return (ARCHIVE_FAILED);
3046 #if defined(__CYGWIN__)
3047 cleanup_pathname_win(path);
3049 /* Skip leading '/'. */
3051 if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
3052 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3053 "Path is ", "absolute");
3054 return (ARCHIVE_FAILED);
3060 /* Scan the pathname one element at a time. */
3062 /* src points to first char after '/' */
3063 if (src[0] == '\0') {
3065 } else if (src[0] == '/') {
3066 /* Found '//', ignore second one. */
3069 } else if (src[0] == '.') {
3070 if (src[1] == '\0') {
3071 /* Ignore trailing '.' */
3073 } else if (src[1] == '/') {
3077 } else if (src[1] == '.') {
3078 if (src[2] == '/' || src[2] == '\0') {
3079 /* Conditionally warn about '..' */
3081 & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3082 fsobj_error(a_eno, a_estr,
3084 "Path contains ", "'..'");
3085 return (ARCHIVE_FAILED);
3089 * Note: Under no circumstances do we
3090 * remove '..' elements. In
3091 * particular, restoring
3092 * '/foo/../bar/' should create the
3093 * 'foo' dir as a side-effect.
3098 /* Copy current element, including leading '/'. */
3101 while (*src != '\0' && *src != '/') {
3108 /* Skip '/' separator. */
3112 * We've just copied zero or more path elements, not including the
3117 * Nothing got copied. The path must have been something
3118 * like '.' or '/' or './' or '/././././/./'.
3125 /* Terminate the result. */
3127 return (ARCHIVE_OK);
3131 cleanup_pathname(struct archive_write_disk *a)
3133 struct archive_string error_string;
3136 archive_string_init(&error_string);
3137 rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3139 if (rc != ARCHIVE_OK) {
3140 archive_set_error(&a->archive, error_number, "%s",
3143 archive_string_free(&error_string);
3148 * Create the parent directory of the specified path, assuming path
3149 * is already in mutable storage.
3152 create_parent_dir(struct archive_write_disk *a, char *path)
3157 /* Remove tail element to obtain parent name. */
3158 slash = strrchr(path, '/');
3160 return (ARCHIVE_OK);
3162 r = create_dir(a, path);
3168 * Create the specified dir, recursing to create parents as necessary.
3170 * Returns ARCHIVE_OK if the path exists when we're done here.
3171 * Otherwise, returns ARCHIVE_FAILED.
3172 * Assumes path is in mutable storage; path is unchanged on exit.
3175 create_dir(struct archive_write_disk *a, char *path)
3178 struct fixup_entry *le;
3180 mode_t mode_final, mode;
3183 /* Check for special names and just skip them. */
3184 slash = strrchr(path, '/');
3190 if (base[0] == '\0' ||
3191 (base[0] == '.' && base[1] == '\0') ||
3192 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
3193 /* Don't bother trying to create null path, '.', or '..'. */
3194 if (slash != NULL) {
3196 r = create_dir(a, path);
3200 return (ARCHIVE_OK);
3204 * Yes, this should be stat() and not lstat(). Using lstat()
3205 * here loses the ability to extract through symlinks. Also note
3206 * that this should not use the a->st cache.
3208 if (la_stat(path, &st) == 0) {
3209 if (S_ISDIR(st.st_mode))
3210 return (ARCHIVE_OK);
3211 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
3212 archive_set_error(&a->archive, EEXIST,
3213 "Can't create directory '%s'", path);
3214 return (ARCHIVE_FAILED);
3216 if (unlink(path) != 0) {
3217 archive_set_error(&a->archive, errno,
3218 "Can't create directory '%s': "
3219 "Conflicting file cannot be removed",
3221 return (ARCHIVE_FAILED);
3223 } else if (errno != ENOENT && errno != ENOTDIR) {
3225 archive_set_error(&a->archive, errno,
3226 "Can't test directory '%s'", path);
3227 return (ARCHIVE_FAILED);
3228 } else if (slash != NULL) {
3230 r = create_dir(a, path);
3232 if (r != ARCHIVE_OK)
3237 * Mode we want for the final restored directory. Per POSIX,
3238 * implicitly-created dirs must be created obeying the umask.
3239 * There's no mention whether this is different for privileged
3240 * restores (which the rest of this code handles by pretending
3241 * umask=0). I've chosen here to always obey the user's umask for
3242 * implicit dirs, even if _EXTRACT_PERM was specified.
3244 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3245 /* Mode we want on disk during the restore process. */
3247 mode |= MINIMUM_DIR_MODE;
3248 mode &= MAXIMUM_DIR_MODE;
3249 if (mkdir(path, mode) == 0) {
3250 if (mode != mode_final) {
3251 le = new_fixup(a, path);
3253 return (ARCHIVE_FATAL);
3254 le->fixup |=TODO_MODE_BASE;
3255 le->mode = mode_final;
3257 return (ARCHIVE_OK);
3261 * Without the following check, a/b/../b/c/d fails at the
3262 * second visit to 'b', so 'd' can't be created. Note that we
3263 * don't add it to the fixup list here, as it's already been
3266 if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3267 return (ARCHIVE_OK);
3269 archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3271 return (ARCHIVE_FAILED);
3275 * Note: Although we can skip setting the user id if the desired user
3276 * id matches the current user, we cannot skip setting the group, as
3277 * many systems set the gid based on the containing directory. So
3278 * we have to perform a chown syscall if we want to set the SGID
3279 * bit. (The alternative is to stat() and then possibly chown(); it's
3280 * more efficient to skip the stat() and just always chown().) Note
3281 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3282 * allows set_mode to skip the stat() check for the GID.
3285 set_ownership(struct archive_write_disk *a)
3287 #if !defined(__CYGWIN__) && !defined(__linux__)
3289 * On Linux, a process may have the CAP_CHOWN capability.
3290 * On Windows there is no 'root' user with uid 0.
3291 * Elsewhere we can skip calling chown if we are not root and the desired
3292 * user id does not match the current user.
3294 if (a->user_uid != 0 && a->user_uid != a->uid) {
3295 archive_set_error(&a->archive, errno,
3296 "Can't set UID=%jd", (intmax_t)a->uid);
3297 return (ARCHIVE_WARN);
3302 /* If we have an fd, we can avoid a race. */
3303 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3304 /* We've set owner and know uid/gid are correct. */
3305 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3306 return (ARCHIVE_OK);
3310 /* We prefer lchown() but will use chown() if that's all we have. */
3311 /* Of course, if we have neither, this will always fail. */
3313 if (lchown(a->name, a->uid, a->gid) == 0) {
3314 /* We've set owner and know uid/gid are correct. */
3315 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3316 return (ARCHIVE_OK);
3319 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3320 /* We've set owner and know uid/gid are correct. */
3321 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3322 return (ARCHIVE_OK);
3326 archive_set_error(&a->archive, errno,
3327 "Can't set user=%jd/group=%jd for %s",
3328 (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3329 return (ARCHIVE_WARN);
3333 * Note: Returns 0 on success, non-zero on failure.
3336 set_time(int fd, int mode, const char *name,
3337 time_t atime, long atime_nsec,
3338 time_t mtime, long mtime_nsec)
3340 /* Select the best implementation for this platform. */
3341 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3343 * utimensat() and futimens() are defined in
3344 * POSIX.1-2008. They support ns resolution and setting times
3345 * on fds and symlinks.
3347 struct timespec ts[2];
3348 (void)mode; /* UNUSED */
3349 ts[0].tv_sec = atime;
3350 ts[0].tv_nsec = atime_nsec;
3351 ts[1].tv_sec = mtime;
3352 ts[1].tv_nsec = mtime_nsec;
3354 return futimens(fd, ts);
3355 return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3359 * The utimes()-family functions support µs-resolution and
3360 * setting times fds and symlinks. utimes() is documented as
3361 * LEGACY by POSIX, futimes() and lutimes() are not described
3364 struct timeval times[2];
3366 times[0].tv_sec = atime;
3367 times[0].tv_usec = atime_nsec / 1000;
3368 times[1].tv_sec = mtime;
3369 times[1].tv_usec = mtime_nsec / 1000;
3373 return (futimes(fd, times));
3375 (void)fd; /* UNUSED */
3378 (void)mode; /* UNUSED */
3379 return (lutimes(name, times));
3383 return (utimes(name, times));
3386 #elif defined(HAVE_UTIME)
3388 * utime() is POSIX-standard but only supports 1s resolution and
3389 * does not support fds or symlinks.
3391 struct utimbuf times;
3392 (void)fd; /* UNUSED */
3393 (void)name; /* UNUSED */
3394 (void)atime_nsec; /* UNUSED */
3395 (void)mtime_nsec; /* UNUSED */
3396 times.actime = atime;
3397 times.modtime = mtime;
3399 return (ARCHIVE_OK);
3400 return (utime(name, ×));
3404 * We don't know how to set the time on this platform.
3406 (void)fd; /* UNUSED */
3407 (void)mode; /* UNUSED */
3408 (void)name; /* UNUSED */
3409 (void)atime_nsec; /* UNUSED */
3410 (void)mtime_nsec; /* UNUSED */
3411 return (ARCHIVE_WARN);
3417 set_time_tru64(int fd, int mode, const char *name,
3418 time_t atime, long atime_nsec,
3419 time_t mtime, long mtime_nsec,
3420 time_t ctime, long ctime_nsec)
3422 struct attr_timbuf tstamp;
3423 tstamp.atime.tv_sec = atime;
3424 tstamp.mtime.tv_sec = mtime;
3425 tstamp.ctime.tv_sec = ctime;
3426 #if defined (__hpux) && defined (__ia64)
3427 tstamp.atime.tv_nsec = atime_nsec;
3428 tstamp.mtime.tv_nsec = mtime_nsec;
3429 tstamp.ctime.tv_nsec = ctime_nsec;
3431 tstamp.atime.tv_usec = atime_nsec / 1000;
3432 tstamp.mtime.tv_usec = mtime_nsec / 1000;
3433 tstamp.ctime.tv_usec = ctime_nsec / 1000;
3435 return (fcntl(fd,F_SETTIMES,&tstamp));
3437 #endif /* F_SETTIMES */
3440 set_times(struct archive_write_disk *a,
3441 int fd, int mode, const char *name,
3442 time_t atime, long atime_nanos,
3443 time_t birthtime, long birthtime_nanos,
3444 time_t mtime, long mtime_nanos,
3445 time_t cctime, long ctime_nanos)
3447 /* Note: set_time doesn't use libarchive return conventions!
3448 * It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */
3453 * on Tru64 try own fcntl first which can restore even the
3454 * ctime, fall back to default code path below if it fails
3455 * or if we are not running as root
3457 if (a->user_uid == 0 &&
3458 set_time_tru64(fd, mode, name,
3459 atime, atime_nanos, mtime,
3460 mtime_nanos, cctime, ctime_nanos) == 0) {
3461 return (ARCHIVE_OK);
3464 (void)cctime; /* UNUSED */
3465 (void)ctime_nanos; /* UNUSED */
3468 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3470 * If you have struct stat.st_birthtime, we assume BSD
3471 * birthtime semantics, in which {f,l,}utimes() updates
3472 * birthtime to earliest mtime. So we set the time twice,
3473 * first using the birthtime, then using the mtime. If
3474 * birthtime == mtime, this isn't necessary, so we skip it.
3475 * If birthtime > mtime, then this won't work, so we skip it.
3477 if (birthtime < mtime
3478 || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3479 r1 = set_time(fd, mode, name,
3481 birthtime, birthtime_nanos);
3483 (void)birthtime; /* UNUSED */
3484 (void)birthtime_nanos; /* UNUSED */
3486 r2 = set_time(fd, mode, name,
3488 mtime, mtime_nanos);
3489 if (r1 != 0 || r2 != 0) {
3490 archive_set_error(&a->archive, errno,
3491 "Can't restore time");
3492 return (ARCHIVE_WARN);
3494 return (ARCHIVE_OK);
3498 set_times_from_entry(struct archive_write_disk *a)
3500 time_t atime, birthtime, mtime, cctime;
3501 long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3503 /* Suitable defaults. */
3504 atime = birthtime = mtime = cctime = a->start_time;
3505 atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3507 /* If no time was provided, we're done. */
3508 if (!archive_entry_atime_is_set(a->entry)
3509 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
3510 && !archive_entry_birthtime_is_set(a->entry)
3512 && !archive_entry_mtime_is_set(a->entry))
3513 return (ARCHIVE_OK);
3515 if (archive_entry_atime_is_set(a->entry)) {
3516 atime = archive_entry_atime(a->entry);
3517 atime_nsec = archive_entry_atime_nsec(a->entry);
3519 if (archive_entry_birthtime_is_set(a->entry)) {
3520 birthtime = archive_entry_birthtime(a->entry);
3521 birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3523 if (archive_entry_mtime_is_set(a->entry)) {
3524 mtime = archive_entry_mtime(a->entry);
3525 mtime_nsec = archive_entry_mtime_nsec(a->entry);
3527 if (archive_entry_ctime_is_set(a->entry)) {
3528 cctime = archive_entry_ctime(a->entry);
3529 ctime_nsec = archive_entry_ctime_nsec(a->entry);
3532 return set_times(a, a->fd, a->mode, a->name,
3534 birthtime, birthtime_nsec,
3536 cctime, ctime_nsec);
3540 set_mode(struct archive_write_disk *a, int mode)
3544 mode &= 07777; /* Strip off file type bits. */
3546 if (a->todo & TODO_SGID_CHECK) {
3548 * If we don't know the GID is right, we must stat()
3549 * to verify it. We can't just check the GID of this
3550 * process, since systems sometimes set GID from
3551 * the enclosing dir or based on ACLs.
3553 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3555 if (a->pst->st_gid != a->gid) {
3557 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3559 * This is only an error if you
3560 * requested owner restore. If you
3561 * didn't, we'll try to restore
3562 * sgid/suid, but won't consider it a
3563 * problem if we can't.
3565 archive_set_error(&a->archive, -1,
3566 "Can't restore SGID bit");
3570 /* While we're here, double-check the UID. */
3571 if (a->pst->st_uid != a->uid
3572 && (a->todo & TODO_SUID)) {
3574 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3575 archive_set_error(&a->archive, -1,
3576 "Can't restore SUID bit");
3580 a->todo &= ~TODO_SGID_CHECK;
3581 a->todo &= ~TODO_SUID_CHECK;
3582 } else if (a->todo & TODO_SUID_CHECK) {
3584 * If we don't know the UID is right, we can just check
3585 * the user, since all systems set the file UID from
3588 if (a->user_uid != a->uid) {
3590 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3591 archive_set_error(&a->archive, -1,
3592 "Can't make file SUID");
3596 a->todo &= ~TODO_SUID_CHECK;
3599 if (S_ISLNK(a->mode)) {
3602 * If this is a symlink, use lchmod(). If the
3603 * platform doesn't support lchmod(), just skip it. A
3604 * platform that doesn't provide a way to set
3605 * permissions on symlinks probably ignores
3606 * permissions on symlinks, so a failure here has no
3609 if (lchmod(a->name, mode) != 0) {
3613 #if ENOTSUP != EOPNOTSUPP
3617 * if lchmod is defined but the platform
3618 * doesn't support it, silently ignore
3623 archive_set_error(&a->archive, errno,
3624 "Can't set permissions to 0%o", (int)mode);
3629 } else if (!S_ISDIR(a->mode)) {
3631 * If it's not a symlink and not a dir, then use
3632 * fchmod() or chmod(), depending on whether we have
3633 * an fd. Dirs get their perms set during the
3634 * post-extract fixup, which is handled elsewhere.
3638 r2 = fchmod(a->fd, mode);
3641 /* If this platform lacks fchmod(), then
3642 * we'll just use chmod(). */
3643 r2 = chmod(a->name, mode);
3646 archive_set_error(&a->archive, errno,
3647 "Can't set permissions to 0%o", (int)mode);
3655 set_fflags(struct archive_write_disk *a)
3657 struct fixup_entry *le;
3658 unsigned long set, clear;
3660 mode_t mode = archive_entry_mode(a->entry);
3662 * Make 'critical_flags' hold all file flags that can't be
3663 * immediately restored. For example, on BSD systems,
3664 * SF_IMMUTABLE prevents hardlinks from being created, so
3665 * should not be set until after any hardlinks are created. To
3666 * preserve some semblance of portability, this uses #ifdef
3667 * extensively. Ugly, but it works.
3669 * Yes, Virginia, this does create a security race. It's mitigated
3670 * somewhat by the practice of creating dirs 0700 until the extract
3671 * is done, but it would be nice if we could do more than that.
3672 * People restoring critical file systems should be wary of
3673 * other programs that might try to muck with files as they're
3676 const int critical_flags = 0
3689 #if defined(FS_APPEND_FL)
3691 #elif defined(EXT2_APPEND_FL)
3694 #if defined(FS_IMMUTABLE_FL)
3696 #elif defined(EXT2_IMMUTABLE_FL)
3699 #ifdef FS_JOURNAL_DATA_FL
3700 | FS_JOURNAL_DATA_FL
3704 if (a->todo & TODO_FFLAGS) {
3705 archive_entry_fflags(a->entry, &set, &clear);
3708 * The first test encourages the compiler to eliminate
3709 * all of this if it's not necessary.
3711 if ((critical_flags != 0) && (set & critical_flags)) {
3712 le = current_fixup(a, a->name);
3714 return (ARCHIVE_FATAL);
3715 le->fixup |= TODO_FFLAGS;
3716 le->fflags_set = set;
3717 /* Store the mode if it's not already there. */
3718 if ((le->fixup & TODO_MODE) == 0)
3721 r = set_fflags_platform(a, a->fd,
3722 a->name, mode, set, clear);
3723 if (r != ARCHIVE_OK)
3727 return (ARCHIVE_OK);
3731 clear_nochange_fflags(struct archive_write_disk *a)
3733 mode_t mode = archive_entry_mode(a->entry);
3734 const int nochange_flags = 0
3747 #ifdef EXT2_APPEND_FL
3750 #ifdef EXT2_IMMUTABLE_FL
3755 return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3760 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3762 * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3765 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3766 mode_t mode, unsigned long set, unsigned long clear)
3769 const int sf_mask = 0
3783 (void)mode; /* UNUSED */
3785 if (set == 0 && clear == 0)
3786 return (ARCHIVE_OK);
3789 * XXX Is the stat here really necessary? Or can I just use
3790 * the 'set' flags directly? In particular, I'm not sure
3791 * about the correct approach if we're overwriting an existing
3792 * file that already has flags on it. XXX
3794 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3797 a->st.st_flags &= ~clear;
3798 a->st.st_flags |= set;
3800 /* Only super-user may change SF_* flags */
3802 if (a->user_uid != 0)
3803 a->st.st_flags &= ~sf_mask;
3805 #ifdef HAVE_FCHFLAGS
3806 /* If platform has fchflags() and we were given an fd, use it. */
3807 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
3808 return (ARCHIVE_OK);
3811 * If we can't use the fd to set the flags, we'll use the
3812 * pathname to set flags. We prefer lchflags() but will use
3813 * chflags() if we must.
3815 #ifdef HAVE_LCHFLAGS
3816 if (lchflags(name, a->st.st_flags) == 0)
3817 return (ARCHIVE_OK);
3818 #elif defined(HAVE_CHFLAGS)
3819 if (S_ISLNK(a->st.st_mode)) {
3820 archive_set_error(&a->archive, errno,
3821 "Can't set file flags on symlink.");
3822 return (ARCHIVE_WARN);
3824 if (chflags(name, a->st.st_flags) == 0)
3825 return (ARCHIVE_OK);
3827 archive_set_error(&a->archive, errno,
3828 "Failed to set file flags");
3829 return (ARCHIVE_WARN);
3832 #elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \
3833 defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
3834 (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \
3835 defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
3837 * Linux uses ioctl() to read and write file flags.
3840 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3841 mode_t mode, unsigned long set, unsigned long clear)
3845 int newflags, oldflags;
3847 * Linux has no define for the flags that are only settable by
3848 * the root user. This code may seem a little complex, but
3849 * there seem to be some Linux systems that lack these
3850 * defines. (?) The code below degrades reasonably gracefully
3851 * if sf_mask is incomplete.
3853 const int sf_mask = 0
3854 #if defined(FS_IMMUTABLE_FL)
3856 #elif defined(EXT2_IMMUTABLE_FL)
3859 #if defined(FS_APPEND_FL)
3861 #elif defined(EXT2_APPEND_FL)
3864 #if defined(FS_JOURNAL_DATA_FL)
3865 | FS_JOURNAL_DATA_FL
3869 if (set == 0 && clear == 0)
3870 return (ARCHIVE_OK);
3871 /* Only regular files and dirs can have flags. */
3872 if (!S_ISREG(mode) && !S_ISDIR(mode))
3873 return (ARCHIVE_OK);
3875 /* If we weren't given an fd, open it ourselves. */
3877 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
3878 __archive_ensure_cloexec_flag(myfd);
3881 return (ARCHIVE_OK);
3884 * XXX As above, this would be way simpler if we didn't have
3885 * to read the current flags from disk. XXX
3889 /* Read the current file flags. */
3891 #ifdef FS_IOC_GETFLAGS
3899 /* Try setting the flags as given. */
3900 newflags = (oldflags & ~clear) | set;
3902 #ifdef FS_IOC_SETFLAGS
3912 /* If we couldn't set all the flags, try again with a subset. */
3913 newflags &= ~sf_mask;
3914 oldflags &= sf_mask;
3915 newflags |= oldflags;
3917 #ifdef FS_IOC_SETFLAGS
3925 /* We couldn't set the flags, so report the failure. */
3927 archive_set_error(&a->archive, errno,
3928 "Failed to set file flags");
3939 * Of course, some systems have neither BSD chflags() nor Linux' flags
3940 * support through ioctl().
3943 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3944 mode_t mode, unsigned long set, unsigned long clear)
3946 (void)a; /* UNUSED */
3947 (void)fd; /* UNUSED */
3948 (void)name; /* UNUSED */
3949 (void)mode; /* UNUSED */
3950 (void)set; /* UNUSED */
3951 (void)clear; /* UNUSED */
3952 return (ARCHIVE_OK);
3955 #endif /* __linux */
3957 #ifndef HAVE_COPYFILE_H
3958 /* Default is to simply drop Mac extended metadata. */
3960 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
3961 const void *metadata, size_t metadata_size)
3963 (void)a; /* UNUSED */
3964 (void)pathname; /* UNUSED */
3965 (void)metadata; /* UNUSED */
3966 (void)metadata_size; /* UNUSED */
3967 return (ARCHIVE_OK);
3971 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
3973 (void)a; /* UNUSED */
3974 (void)pathname; /* UNUSED */
3975 return (ARCHIVE_OK);
3980 * On Mac OS, we use copyfile() to unpack the metadata and
3981 * apply it to the target file.
3984 #if defined(HAVE_SYS_XATTR_H)
3986 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
3989 char *xattr_names = NULL, *xattr_val = NULL;
3990 int ret = ARCHIVE_OK, xattr_i;
3992 xattr_size = flistxattr(tmpfd, NULL, 0, 0);
3993 if (xattr_size == -1) {
3994 archive_set_error(&a->archive, errno,
3995 "Failed to read metadata(xattr)");
3999 xattr_names = malloc(xattr_size);
4000 if (xattr_names == NULL) {
4001 archive_set_error(&a->archive, ENOMEM,
4002 "Can't allocate memory for metadata(xattr)");
4003 ret = ARCHIVE_FATAL;
4006 xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
4007 if (xattr_size == -1) {
4008 archive_set_error(&a->archive, errno,
4009 "Failed to read metadata(xattr)");
4013 for (xattr_i = 0; xattr_i < xattr_size;
4014 xattr_i += strlen(xattr_names + xattr_i) + 1) {
4015 char *xattr_val_saved;
4019 s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
4021 archive_set_error(&a->archive, errno,
4022 "Failed to get metadata(xattr)");
4026 xattr_val_saved = xattr_val;
4027 xattr_val = realloc(xattr_val, s);
4028 if (xattr_val == NULL) {
4029 archive_set_error(&a->archive, ENOMEM,
4030 "Failed to get metadata(xattr)");
4032 free(xattr_val_saved);
4035 s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4037 archive_set_error(&a->archive, errno,
4038 "Failed to get metadata(xattr)");
4042 f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4044 archive_set_error(&a->archive, errno,
4045 "Failed to get metadata(xattr)");
4058 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
4060 #ifndef HAVE_SYS_ACL_H
4063 acl_t acl, dfacl = NULL;
4064 int acl_r, ret = ARCHIVE_OK;
4066 acl = acl_get_fd(tmpfd);
4068 if (errno == ENOENT)
4069 /* There are not any ACLs. */
4071 archive_set_error(&a->archive, errno,
4072 "Failed to get metadata(acl)");
4076 dfacl = acl_dup(acl);
4077 acl_r = acl_set_fd(dffd, dfacl);
4079 archive_set_error(&a->archive, errno,
4080 "Failed to get metadata(acl)");
4094 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4096 struct archive_string tmpdatafork;
4099 archive_string_init(&tmpdatafork);
4100 archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
4101 tmpfd = mkstemp(tmpdatafork.s);
4103 archive_set_error(&a->archive, errno,
4104 "Failed to mkstemp");
4105 archive_string_free(&tmpdatafork);
4108 if (copyfile(pathname, tmpdatafork.s, 0,
4109 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4110 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4111 archive_set_error(&a->archive, errno,
4112 "Failed to restore metadata");
4116 unlink(tmpdatafork.s);
4117 archive_string_free(&tmpdatafork);
4122 copy_metadata(struct archive_write_disk *a, const char *metadata,
4123 const char *datafork, int datafork_compressed)
4125 int ret = ARCHIVE_OK;
4127 if (datafork_compressed) {
4130 tmpfd = create_tempdatafork(a, metadata);
4132 return (ARCHIVE_WARN);
4135 * Do not open the data fork compressed by HFS+ compression
4136 * with at least a writing mode(O_RDWR or O_WRONLY). it
4137 * makes the data fork uncompressed.
4139 dffd = open(datafork, 0);
4141 archive_set_error(&a->archive, errno,
4142 "Failed to open the data fork for metadata");
4144 return (ARCHIVE_WARN);
4147 #if defined(HAVE_SYS_XATTR_H)
4148 ret = copy_xattrs(a, tmpfd, dffd);
4149 if (ret == ARCHIVE_OK)
4151 ret = copy_acls(a, tmpfd, dffd);
4155 if (copyfile(metadata, datafork, 0,
4156 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4157 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4158 archive_set_error(&a->archive, errno,
4159 "Failed to restore metadata");
4167 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4168 const void *metadata, size_t metadata_size)
4170 struct archive_string tmp;
4173 int ret = ARCHIVE_OK;
4175 /* This would be simpler if copyfile() could just accept the
4176 * metadata as a block of memory; then we could sidestep this
4177 * silly dance of writing the data to disk just so that
4178 * copyfile() can read it back in again. */
4179 archive_string_init(&tmp);
4180 archive_strcpy(&tmp, pathname);
4181 archive_strcat(&tmp, ".XXXXXX");
4182 fd = mkstemp(tmp.s);
4185 archive_set_error(&a->archive, errno,
4186 "Failed to restore metadata");
4187 archive_string_free(&tmp);
4188 return (ARCHIVE_WARN);
4190 written = write(fd, metadata, metadata_size);
4192 if ((size_t)written != metadata_size) {
4193 archive_set_error(&a->archive, errno,
4194 "Failed to restore metadata");
4199 #if defined(UF_COMPRESSED)
4200 if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
4201 (ret = lazy_stat(a)) == ARCHIVE_OK)
4202 compressed = a->st.st_flags & UF_COMPRESSED;
4206 ret = copy_metadata(a, tmp.s, pathname, compressed);
4209 archive_string_free(&tmp);
4214 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4219 struct archive_string datafork;
4220 int fd = -1, ret = ARCHIVE_OK;
4222 archive_string_init(&datafork);
4223 /* Check if the current file name is a type of the resource
4225 p = strrchr(pathname, '/');
4230 if (p[0] != '.' || p[1] != '_')
4231 goto skip_appledouble;
4234 * Check if the data fork file exists.
4236 * TODO: Check if this write disk object has handled it.
4238 archive_strncpy(&datafork, pathname, p - pathname);
4239 archive_strcat(&datafork, p + 2);
4240 if (lstat(datafork.s, &st) == -1 ||
4241 (st.st_mode & AE_IFMT) != AE_IFREG)
4242 goto skip_appledouble;
4245 * Check if the file is in the AppleDouble form.
4247 fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4248 __archive_ensure_cloexec_flag(fd);
4250 archive_set_error(&a->archive, errno,
4251 "Failed to open a restoring file");
4253 goto skip_appledouble;
4255 if (read(fd, buff, 8) == -1) {
4256 archive_set_error(&a->archive, errno,
4257 "Failed to read a restoring file");
4260 goto skip_appledouble;
4263 /* Check AppleDouble Magic Code. */
4264 if (archive_be32dec(buff) != 0x00051607)
4265 goto skip_appledouble;
4266 /* Check AppleDouble Version. */
4267 if (archive_be32dec(buff+4) != 0x00020000)
4268 goto skip_appledouble;
4270 ret = copy_metadata(a, pathname, datafork.s,
4271 #if defined(UF_COMPRESSED)
4272 st.st_flags & UF_COMPRESSED);
4276 if (ret == ARCHIVE_OK) {
4281 archive_string_free(&datafork);
4286 #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4288 * Restore extended attributes - Linux, Darwin and AIX implementations:
4289 * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4292 set_xattrs(struct archive_write_disk *a)
4294 struct archive_entry *entry = a->entry;
4295 struct archive_string errlist;
4296 int ret = ARCHIVE_OK;
4297 int i = archive_entry_xattr_reset(entry);
4300 archive_string_init(&errlist);
4308 archive_entry_xattr_next(entry, &name, &value, &size);
4312 #if ARCHIVE_XATTR_LINUX
4313 /* Linux: quietly skip POSIX.1e ACL extended attributes */
4314 if (strncmp(name, "system.", 7) == 0 &&
4315 (strcmp(name + 7, "posix_acl_access") == 0 ||
4316 strcmp(name + 7, "posix_acl_default") == 0))
4318 if (strncmp(name, "trusted.SGI_", 12) == 0 &&
4319 (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
4320 strcmp(name + 12, "ACL_FILE") == 0))
4323 /* Linux: xfsroot namespace is obsolete and unsupported */
4324 if (strncmp(name, "xfsroot.", 8) == 0) {
4326 archive_strcat(&errlist, name);
4327 archive_strappend_char(&errlist, ' ');
4333 #if ARCHIVE_XATTR_LINUX
4334 e = fsetxattr(a->fd, name, value, size, 0);
4335 #elif ARCHIVE_XATTR_DARWIN
4336 e = fsetxattr(a->fd, name, value, size, 0, 0);
4337 #elif ARCHIVE_XATTR_AIX
4338 e = fsetea(a->fd, name, value, size, 0);
4341 #if ARCHIVE_XATTR_LINUX
4342 e = lsetxattr(archive_entry_pathname(entry),
4343 name, value, size, 0);
4344 #elif ARCHIVE_XATTR_DARWIN
4345 e = setxattr(archive_entry_pathname(entry),
4346 name, value, size, 0, XATTR_NOFOLLOW);
4347 #elif ARCHIVE_XATTR_AIX
4348 e = lsetea(archive_entry_pathname(entry),
4349 name, value, size, 0);
4354 archive_strcat(&errlist, name);
4355 archive_strappend_char(&errlist, ' ');
4356 if (errno != ENOTSUP && errno != ENOSYS)
4361 if (ret == ARCHIVE_WARN) {
4362 if (fail && errlist.length > 0) {
4364 errlist.s[errlist.length] = '\0';
4365 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4366 "Cannot restore extended attributes: %s",
4369 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4370 "Cannot restore extended "
4371 "attributes on this file system.");
4374 archive_string_free(&errlist);
4377 #elif ARCHIVE_XATTR_FREEBSD
4379 * Restore extended attributes - FreeBSD implementation
4382 set_xattrs(struct archive_write_disk *a)
4384 struct archive_entry *entry = a->entry;
4385 struct archive_string errlist;
4386 int ret = ARCHIVE_OK;
4387 int i = archive_entry_xattr_reset(entry);
4390 archive_string_init(&errlist);
4396 archive_entry_xattr_next(entry, &name, &value, &size);
4401 namespace = EXTATTR_NAMESPACE_USER;
4403 if (strncmp(name, "user.", 5) == 0) {
4404 /* "user." attributes go to user namespace */
4406 namespace = EXTATTR_NAMESPACE_USER;
4407 } else if (strncmp(name, "system.", 7) == 0) {
4409 namespace = EXTATTR_NAMESPACE_SYSTEM;
4410 if (!strcmp(name, "nfs4.acl") ||
4411 !strcmp(name, "posix1e.acl_access") ||
4412 !strcmp(name, "posix1e.acl_default"))
4415 /* Other namespaces are unsupported */
4416 archive_strcat(&errlist, name);
4417 archive_strappend_char(&errlist, ' ');
4425 * On FreeBSD, extattr_set_fd does not
4426 * return the same as
4427 * extattr_set_file. It returns zero
4428 * on success, non-zero on failure.
4430 * We can detect the failure by
4431 * manually setting errno prior to the
4432 * call and checking after.
4434 * If errno remains zero, fake the
4435 * return value by setting e to size.
4437 * This is a hack for now until I
4438 * (Shawn Webb) get FreeBSD to fix the
4439 * issue, if that's even possible.
4442 e = extattr_set_fd(a->fd, namespace, name,
4444 if (e == 0 && errno == 0) {
4448 e = extattr_set_link(
4449 archive_entry_pathname(entry), namespace,
4452 if (e != (ssize_t)size) {
4453 archive_strcat(&errlist, name);
4454 archive_strappend_char(&errlist, ' ');
4456 if (errno != ENOTSUP && errno != ENOSYS)
4462 if (ret == ARCHIVE_WARN) {
4463 if (fail && errlist.length > 0) {
4465 errlist.s[errlist.length] = '\0';
4467 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4468 "Cannot restore extended attributes: %s",
4471 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4472 "Cannot restore extended "
4473 "attributes on this file system.");
4476 archive_string_free(&errlist);
4481 * Restore extended attributes - stub implementation for unsupported systems
4484 set_xattrs(struct archive_write_disk *a)
4486 static int warning_done = 0;
4488 /* If there aren't any extended attributes, then it's okay not
4489 * to extract them, otherwise, issue a single warning. */
4490 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4492 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4493 "Cannot restore extended attributes on this system");
4494 return (ARCHIVE_WARN);
4496 /* Warning was already emitted; suppress further warnings. */
4497 return (ARCHIVE_OK);
4502 * Test if file on disk is older than entry.
4505 older(struct stat *st, struct archive_entry *entry)
4507 /* First, test the seconds and return if we have a definite answer. */
4508 /* Definitely older. */
4509 if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry)))
4511 /* Definitely younger. */
4512 if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4514 /* If this platform supports fractional seconds, try those. */
4515 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4516 /* Definitely older. */
4517 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4519 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4520 /* Definitely older. */
4521 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4523 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4525 if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4527 #elif HAVE_STRUCT_STAT_ST_UMTIME
4529 if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4531 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4533 if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4536 /* This system doesn't have high-res timestamps. */
4538 /* Same age or newer, so not older. */
4542 #ifndef ARCHIVE_ACL_SUPPORT
4544 archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4545 struct archive_acl *abstract_acl, __LA_MODE_T mode)
4547 (void)a; /* UNUSED */
4548 (void)fd; /* UNUSED */
4549 (void)name; /* UNUSED */
4550 (void)abstract_acl; /* UNUSED */
4551 (void)mode; /* UNUSED */
4552 return (ARCHIVE_OK);
4556 #endif /* !_WIN32 || __CYGWIN__ */