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;
551 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
552 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
553 "archive_write_disk_header");
554 archive_clear_error(&a->archive);
555 if (a->archive.state & ARCHIVE_STATE_DATA) {
556 r = _archive_write_disk_finish_entry(&a->archive);
557 if (r == ARCHIVE_FATAL)
561 /* Set up for this particular entry. */
563 a->current_fixup = NULL;
566 archive_entry_free(a->entry);
569 a->entry = archive_entry_clone(entry);
574 a->uid = a->user_uid;
575 a->mode = archive_entry_mode(a->entry);
576 if (archive_entry_size_is_set(a->entry))
577 a->filesize = archive_entry_size(a->entry);
580 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
581 a->name = a->_name_data.s;
582 archive_clear_error(&a->archive);
585 * Clean up the requested path. This is necessary for correct
586 * dir restores; the dir restore logic otherwise gets messed
587 * up by nonsense like "dir/.".
589 ret = cleanup_pathname(a);
590 if (ret != ARCHIVE_OK)
594 * Query the umask so we get predictable mode settings.
595 * This gets done on every call to _write_header in case the
596 * user edits their umask during the extraction for some
599 umask(a->user_umask = umask(0));
601 /* Figure out what we need to do for this entry. */
602 a->todo = TODO_MODE_BASE;
603 if (a->flags & ARCHIVE_EXTRACT_PERM) {
604 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
606 * SGID requires an extra "check" step because we
607 * cannot easily predict the GID that the system will
608 * assign. (Different systems assign GIDs to files
609 * based on a variety of criteria, including process
610 * credentials and the gid of the enclosing
611 * directory.) We can only restore the SGID bit if
612 * the file has the right GID, and we only know the
613 * GID if we either set it (see set_ownership) or if
614 * we've actually called stat() on the file after it
615 * was restored. Since there are several places at
616 * which we might verify the GID, we need a TODO bit
619 if (a->mode & S_ISGID)
620 a->todo |= TODO_SGID | TODO_SGID_CHECK;
622 * Verifying the SUID is simpler, but can still be
623 * done in multiple ways, hence the separate "check" bit.
625 if (a->mode & S_ISUID)
626 a->todo |= TODO_SUID | TODO_SUID_CHECK;
629 * User didn't request full permissions, so don't
630 * restore SUID, SGID bits and obey umask.
635 a->mode &= ~a->user_umask;
637 if (a->flags & ARCHIVE_EXTRACT_OWNER)
638 a->todo |= TODO_OWNER;
639 if (a->flags & ARCHIVE_EXTRACT_TIME)
640 a->todo |= TODO_TIMES;
641 if (a->flags & ARCHIVE_EXTRACT_ACL) {
642 #if ARCHIVE_ACL_DARWIN
644 * On MacOS, platform ACLs get stored in mac_metadata, too.
645 * If we intend to extract mac_metadata and it is present
646 * we skip extracting libarchive NFSv4 ACLs.
648 size_t metadata_size;
650 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
651 archive_entry_mac_metadata(a->entry,
652 &metadata_size) == NULL || metadata_size == 0)
654 #if ARCHIVE_ACL_LIBRICHACL
656 * RichACLs are stored in an extended attribute.
657 * If we intend to extract extended attributes and have this
658 * attribute we skip extracting libarchive NFSv4 ACLs.
660 short extract_acls = 1;
661 if (a->flags & ARCHIVE_EXTRACT_XATTR && (
662 archive_entry_acl_types(a->entry) &
663 ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
664 const char *attr_name;
665 const void *attr_value;
667 int i = archive_entry_xattr_reset(a->entry);
669 archive_entry_xattr_next(a->entry, &attr_name,
670 &attr_value, &attr_size);
671 if (attr_name != NULL && attr_value != NULL &&
672 attr_size > 0 && strcmp(attr_name,
673 "trusted.richacl") == 0) {
681 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
684 if (archive_entry_filetype(a->entry) == AE_IFDIR)
685 a->deferred |= TODO_ACLS;
687 a->todo |= TODO_ACLS;
688 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
692 if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
693 if (archive_entry_filetype(a->entry) == AE_IFDIR)
694 a->deferred |= TODO_MAC_METADATA;
696 a->todo |= TODO_MAC_METADATA;
698 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
699 if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
700 unsigned long set, clear;
701 archive_entry_fflags(a->entry, &set, &clear);
702 if ((set & ~clear) & UF_COMPRESSED) {
703 a->todo |= TODO_HFS_COMPRESSION;
704 a->decmpfs_block_count = (unsigned)-1;
707 if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
708 (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
709 a->todo |= TODO_HFS_COMPRESSION;
710 a->decmpfs_block_count = (unsigned)-1;
715 /* Check if the current file name is a type of the
716 * resource fork file. */
717 p = strrchr(a->name, '/');
722 if (p[0] == '.' && p[1] == '_') {
723 /* Do not compress "._XXX" files. */
724 a->todo &= ~TODO_HFS_COMPRESSION;
726 a->todo |= TODO_APPLEDOUBLE;
731 if (a->flags & ARCHIVE_EXTRACT_XATTR) {
732 #if ARCHIVE_XATTR_DARWIN
734 * On MacOS, extended attributes get stored in mac_metadata,
735 * too. If we intend to extract mac_metadata and it is present
736 * we skip extracting extended attributes.
738 size_t metadata_size;
740 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
741 archive_entry_mac_metadata(a->entry,
742 &metadata_size) == NULL || metadata_size == 0)
744 a->todo |= TODO_XATTR;
746 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
747 a->todo |= TODO_FFLAGS;
748 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
749 ret = check_symlinks(a);
750 if (ret != ARCHIVE_OK)
753 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
754 /* If path exceeds PATH_MAX, shorten the path. */
755 edit_deep_directories(a);
758 ret = restore_entry(a);
760 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
762 * Check if the filesystem the file is restoring on supports
763 * HFS+ Compression. If not, cancel HFS+ Compression.
765 if (a->todo | TODO_HFS_COMPRESSION) {
767 * NOTE: UF_COMPRESSED is ignored even if the filesystem
768 * supports HFS+ Compression because the file should
769 * have at least an extended attribute "com.apple.decmpfs"
770 * before the flag is set to indicate that the file have
771 * been compressed. If the filesystem does not support
772 * HFS+ Compression the system call will fail.
774 if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
775 a->todo &= ~TODO_HFS_COMPRESSION;
780 * TODO: There are rumours that some extended attributes must
781 * be restored before file data is written. If this is true,
782 * then we either need to write all extended attributes both
783 * before and after restoring the data, or find some rule for
784 * determining which must go first and which last. Due to the
785 * many ways people are using xattrs, this may prove to be an
786 * intractable problem.
790 /* If we changed directory above, restore it here. */
791 if (a->restore_pwd >= 0) {
792 r = fchdir(a->restore_pwd);
794 archive_set_error(&a->archive, errno,
798 close(a->restore_pwd);
804 * Fixup uses the unedited pathname from archive_entry_pathname(),
805 * because it is relative to the base dir and the edited path
806 * might be relative to some intermediate dir as a result of the
807 * deep restore logic.
809 if (a->deferred & TODO_MODE) {
810 fe = current_fixup(a, archive_entry_pathname(entry));
812 return (ARCHIVE_FATAL);
813 fe->fixup |= TODO_MODE_BASE;
817 if ((a->deferred & TODO_TIMES)
818 && (archive_entry_mtime_is_set(entry)
819 || archive_entry_atime_is_set(entry))) {
820 fe = current_fixup(a, archive_entry_pathname(entry));
822 return (ARCHIVE_FATAL);
824 fe->fixup |= TODO_TIMES;
825 if (archive_entry_atime_is_set(entry)) {
826 fe->atime = archive_entry_atime(entry);
827 fe->atime_nanos = archive_entry_atime_nsec(entry);
829 /* If atime is unset, use start time. */
830 fe->atime = a->start_time;
833 if (archive_entry_mtime_is_set(entry)) {
834 fe->mtime = archive_entry_mtime(entry);
835 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
837 /* If mtime is unset, use start time. */
838 fe->mtime = a->start_time;
841 if (archive_entry_birthtime_is_set(entry)) {
842 fe->birthtime = archive_entry_birthtime(entry);
843 fe->birthtime_nanos = archive_entry_birthtime_nsec(
846 /* If birthtime is unset, use mtime. */
847 fe->birthtime = fe->mtime;
848 fe->birthtime_nanos = fe->mtime_nanos;
852 if (a->deferred & TODO_ACLS) {
853 fe = current_fixup(a, archive_entry_pathname(entry));
855 return (ARCHIVE_FATAL);
856 fe->fixup |= TODO_ACLS;
857 archive_acl_copy(&fe->acl, archive_entry_acl(entry));
860 if (a->deferred & TODO_MAC_METADATA) {
861 const void *metadata;
862 size_t metadata_size;
863 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
864 if (metadata != NULL && metadata_size > 0) {
865 fe = current_fixup(a, archive_entry_pathname(entry));
867 return (ARCHIVE_FATAL);
868 fe->mac_metadata = malloc(metadata_size);
869 if (fe->mac_metadata != NULL) {
870 memcpy(fe->mac_metadata, metadata,
872 fe->mac_metadata_size = metadata_size;
873 fe->fixup |= TODO_MAC_METADATA;
878 if (a->deferred & TODO_FFLAGS) {
879 fe = current_fixup(a, archive_entry_pathname(entry));
881 return (ARCHIVE_FATAL);
882 fe->fixup |= TODO_FFLAGS;
883 /* TODO: Complete this.. defer fflags from below. */
886 /* We've created the object and are ready to pour data into it. */
887 if (ret >= ARCHIVE_WARN)
888 a->archive.state = ARCHIVE_STATE_DATA;
890 * If it's not open, tell our client not to try writing.
891 * In particular, dirs, links, etc, don't get written to.
894 archive_entry_set_size(entry, 0);
902 archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
904 struct archive_write_disk *a = (struct archive_write_disk *)_a;
905 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
906 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
907 a->skip_file_set = 1;
908 a->skip_file_dev = d;
909 a->skip_file_ino = i;
914 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
916 uint64_t start_size = size;
917 ssize_t bytes_written = 0;
918 ssize_t block_size = 0, bytes_to_write;
923 if (a->filesize == 0 || a->fd < 0) {
924 archive_set_error(&a->archive, 0,
925 "Attempt to write to an empty file");
926 return (ARCHIVE_WARN);
929 if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
930 #if HAVE_STRUCT_STAT_ST_BLKSIZE
932 if ((r = lazy_stat(a)) != ARCHIVE_OK)
934 block_size = a->pst->st_blksize;
936 /* XXX TODO XXX Is there a more appropriate choice here ? */
937 /* This needn't match the filesystem allocation size. */
938 block_size = 16*1024;
942 /* If this write would run beyond the file size, truncate it. */
943 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
944 start_size = size = (size_t)(a->filesize - a->offset);
946 /* Write the data. */
948 if (block_size == 0) {
949 bytes_to_write = size;
951 /* We're sparsifying the file. */
955 /* Skip leading zero bytes. */
956 for (p = buff, end = buff + size; p < end; ++p) {
960 a->offset += p - buff;
966 /* Calculate next block boundary after offset. */
968 = (a->offset / block_size + 1) * block_size;
970 /* If the adjusted write would cross block boundary,
971 * truncate it to the block boundary. */
972 bytes_to_write = size;
973 if (a->offset + bytes_to_write > block_end)
974 bytes_to_write = block_end - a->offset;
976 /* Seek if necessary to the specified offset. */
977 if (a->offset != a->fd_offset) {
978 if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
979 archive_set_error(&a->archive, errno,
981 return (ARCHIVE_FATAL);
983 a->fd_offset = a->offset;
985 bytes_written = write(a->fd, buff, bytes_to_write);
986 if (bytes_written < 0) {
987 archive_set_error(&a->archive, errno, "Write failed");
988 return (ARCHIVE_WARN);
990 buff += bytes_written;
991 size -= bytes_written;
992 a->total_bytes_written += bytes_written;
993 a->offset += bytes_written;
994 a->fd_offset = a->offset;
996 return (start_size - size);
999 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
1000 && defined(HAVE_ZLIB_H)
1003 * Set UF_COMPRESSED file flag.
1004 * This have to be called after hfs_write_decmpfs() because if the
1005 * file does not have "com.apple.decmpfs" xattr the flag is ignored.
1008 hfs_set_compressed_fflag(struct archive_write_disk *a)
1012 if ((r = lazy_stat(a)) != ARCHIVE_OK)
1015 a->st.st_flags |= UF_COMPRESSED;
1016 if (fchflags(a->fd, a->st.st_flags) != 0) {
1017 archive_set_error(&a->archive, errno,
1018 "Failed to set UF_COMPRESSED file flag");
1019 return (ARCHIVE_WARN);
1021 return (ARCHIVE_OK);
1025 * HFS+ Compression decmpfs
1027 * +------------------------------+ +0
1028 * | Magic(LE 4 bytes) |
1029 * +------------------------------+
1030 * | Type(LE 4 bytes) |
1031 * +------------------------------+
1032 * | Uncompressed size(LE 8 bytes)|
1033 * +------------------------------+ +16
1035 * | Compressed data |
1036 * | (Placed only if Type == 3) |
1038 * +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE
1040 * Type is 3: decmpfs has compressed data.
1041 * Type is 4: Resource Fork has compressed data.
1044 * Write "com.apple.decmpfs"
1047 hfs_write_decmpfs(struct archive_write_disk *a)
1050 uint32_t compression_type;
1052 r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1053 a->decmpfs_attr_size, 0, 0);
1055 archive_set_error(&a->archive, errno,
1056 "Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
1057 compression_type = archive_le32dec(
1058 &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
1059 if (compression_type == CMP_RESOURCE_FORK)
1060 fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
1061 XATTR_SHOWCOMPRESSION);
1062 return (ARCHIVE_WARN);
1064 return (ARCHIVE_OK);
1068 * HFS+ Compression Resource Fork
1070 * +-----------------------------+
1071 * | Header(260 bytes) |
1072 * +-----------------------------+
1073 * | Block count(LE 4 bytes) |
1074 * +-----------------------------+ --+
1075 * +-- | Offset (LE 4 bytes) | |
1076 * | | [distance from Block count] | | Block 0
1077 * | +-----------------------------+ |
1078 * | | Compressed size(LE 4 bytes) | |
1079 * | +-----------------------------+ --+
1081 * | | .................. |
1083 * | +-----------------------------+ --+
1084 * | | Offset (LE 4 bytes) | |
1085 * | +-----------------------------+ | Block (Block count -1)
1086 * | | Compressed size(LE 4 bytes) | |
1087 * +-> +-----------------------------+ --+
1088 * | Compressed data(n bytes) | Block 0
1089 * +-----------------------------+
1091 * | .................. |
1093 * +-----------------------------+
1094 * | Compressed data(n bytes) | Block (Block count -1)
1095 * +-----------------------------+
1096 * | Footer(50 bytes) |
1097 * +-----------------------------+
1101 * Write the header of "com.apple.ResourceFork"
1104 hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1105 size_t bytes, uint32_t position)
1109 ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1110 position, a->rsrc_xattr_options);
1112 archive_set_error(&a->archive, errno,
1113 "Cannot restore xattr: %s at %u pos %u bytes",
1114 XATTR_RESOURCEFORK_NAME,
1117 return (ARCHIVE_WARN);
1119 a->rsrc_xattr_options &= ~XATTR_CREATE;
1120 return (ARCHIVE_OK);
1124 hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1128 ret = hfs_write_resource_fork(a, a->compressed_buffer,
1129 bytes_compressed, a->compressed_rsrc_position);
1130 if (ret == ARCHIVE_OK)
1131 a->compressed_rsrc_position += bytes_compressed;
1136 hfs_write_resource_fork_header(struct archive_write_disk *a)
1138 unsigned char *buff;
1139 uint32_t rsrc_bytes;
1140 uint32_t rsrc_header_bytes;
1143 * Write resource fork header + block info.
1145 buff = a->resource_fork;
1146 rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1148 RSRC_H_SIZE + /* Header base size. */
1149 4 + /* Block count. */
1150 (a->decmpfs_block_count * 8);/* Block info */
1151 archive_be32enc(buff, 0x100);
1152 archive_be32enc(buff + 4, rsrc_bytes);
1153 archive_be32enc(buff + 8, rsrc_bytes - 256);
1154 archive_be32enc(buff + 12, 0x32);
1155 memset(buff + 16, 0, 240);
1156 archive_be32enc(buff + 256, rsrc_bytes - 260);
1157 return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
1161 hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1163 static const char rsrc_footer[RSRC_F_SIZE] = {
1164 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1165 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1166 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1167 0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm',
1168 'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
1169 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1172 if (buff_size < sizeof(rsrc_footer))
1174 memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1175 return (sizeof(rsrc_footer));
1179 hfs_reset_compressor(struct archive_write_disk *a)
1183 if (a->stream_valid)
1184 ret = deflateReset(&a->stream);
1186 ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1189 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1190 "Failed to initialize compressor");
1191 return (ARCHIVE_FATAL);
1193 a->stream_valid = 1;
1195 return (ARCHIVE_OK);
1199 hfs_decompress(struct archive_write_disk *a)
1201 uint32_t *block_info;
1202 unsigned int block_count;
1203 uint32_t data_pos, data_size;
1205 ssize_t bytes_written, bytes_to_write;
1208 block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1209 block_count = archive_le32dec(block_info++);
1210 while (block_count--) {
1211 data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
1212 data_size = archive_le32dec(block_info++);
1213 r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
1214 a->compressed_buffer, data_size, data_pos, 0);
1215 if (r != data_size) {
1216 archive_set_error(&a->archive,
1217 (r < 0)?errno:ARCHIVE_ERRNO_MISC,
1218 "Failed to read resource fork");
1219 return (ARCHIVE_WARN);
1221 if (a->compressed_buffer[0] == 0xff) {
1222 bytes_to_write = data_size -1;
1223 b = a->compressed_buffer + 1;
1225 uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1228 zr = uncompress((Bytef *)a->uncompressed_buffer,
1229 &dest_len, a->compressed_buffer, data_size);
1231 archive_set_error(&a->archive,
1233 "Failed to decompress resource fork");
1234 return (ARCHIVE_WARN);
1236 bytes_to_write = dest_len;
1237 b = (unsigned char *)a->uncompressed_buffer;
1240 bytes_written = write(a->fd, b, bytes_to_write);
1241 if (bytes_written < 0) {
1242 archive_set_error(&a->archive, errno,
1244 return (ARCHIVE_WARN);
1246 bytes_to_write -= bytes_written;
1248 } while (bytes_to_write > 0);
1250 r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1252 archive_set_error(&a->archive, errno,
1253 "Failed to remove resource fork");
1254 return (ARCHIVE_WARN);
1256 return (ARCHIVE_OK);
1260 hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1263 unsigned char *buffer_compressed;
1264 size_t bytes_compressed;
1268 ret = hfs_reset_compressor(a);
1269 if (ret != ARCHIVE_OK)
1272 if (a->compressed_buffer == NULL) {
1275 block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
1276 + compressBound(MAX_DECMPFS_BLOCK_SIZE);
1277 a->compressed_buffer = malloc(block_size);
1278 if (a->compressed_buffer == NULL) {
1279 archive_set_error(&a->archive, ENOMEM,
1280 "Can't allocate memory for Resource Fork");
1281 return (ARCHIVE_FATAL);
1283 a->compressed_buffer_size = block_size;
1284 a->compressed_buffer_remaining = block_size;
1287 buffer_compressed = a->compressed_buffer +
1288 a->compressed_buffer_size - a->compressed_buffer_remaining;
1289 a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
1290 a->stream.avail_in = size;
1291 a->stream.next_out = buffer_compressed;
1292 a->stream.avail_out = a->compressed_buffer_remaining;
1294 ret = deflate(&a->stream, Z_FINISH);
1300 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1301 "Failed to compress data");
1302 return (ARCHIVE_FAILED);
1304 } while (ret == Z_OK);
1305 bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1308 * If the compressed size is larger than the original size,
1309 * throw away compressed data, use uncompressed data instead.
1311 if (bytes_compressed > size) {
1312 buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1313 memcpy(buffer_compressed + 1, buff, size);
1314 bytes_compressed = size + 1;
1316 a->compressed_buffer_remaining -= bytes_compressed;
1319 * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
1320 * and the block count in the file is only one, store compressed
1321 * data to decmpfs xattr instead of the resource fork.
1323 if (a->decmpfs_block_count == 1 &&
1324 (a->decmpfs_attr_size + bytes_compressed)
1325 <= MAX_DECMPFS_XATTR_SIZE) {
1326 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1328 memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
1329 buffer_compressed, bytes_compressed);
1330 a->decmpfs_attr_size += bytes_compressed;
1331 a->compressed_buffer_remaining = a->compressed_buffer_size;
1333 * Finish HFS+ Compression.
1334 * - Write the decmpfs xattr.
1335 * - Set the UF_COMPRESSED file flag.
1337 ret = hfs_write_decmpfs(a);
1338 if (ret == ARCHIVE_OK)
1339 ret = hfs_set_compressed_fflag(a);
1343 /* Update block info. */
1344 archive_le32enc(a->decmpfs_block_info++,
1345 a->compressed_rsrc_position_v - RSRC_H_SIZE);
1346 archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
1347 a->compressed_rsrc_position_v += bytes_compressed;
1350 * Write the compressed data to the resource fork.
1352 bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
1353 while (bytes_used >= COMPRESSED_W_SIZE) {
1354 ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
1355 if (ret != ARCHIVE_OK)
1357 bytes_used -= COMPRESSED_W_SIZE;
1358 if (bytes_used > COMPRESSED_W_SIZE)
1359 memmove(a->compressed_buffer,
1360 a->compressed_buffer + COMPRESSED_W_SIZE,
1363 memcpy(a->compressed_buffer,
1364 a->compressed_buffer + COMPRESSED_W_SIZE,
1367 a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1370 * If the current block is the last block, write the remaining
1371 * compressed data and the resource fork footer.
1373 if (a->file_remaining_bytes == 0) {
1377 /* Append the resource footer. */
1378 rsrc_size = hfs_set_resource_fork_footer(
1379 a->compressed_buffer + bytes_used,
1380 a->compressed_buffer_remaining);
1381 ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
1382 a->compressed_buffer_remaining = a->compressed_buffer_size;
1384 /* If the compressed size is not enough smaller than
1385 * the uncompressed size. cancel HFS+ compression.
1386 * TODO: study a behavior of ditto utility and improve
1387 * the condition to fall back into no HFS+ compression. */
1388 bk = HFS_BLOCKS(a->compressed_rsrc_position);
1390 if (bk > HFS_BLOCKS(a->filesize))
1391 return hfs_decompress(a);
1393 * Write the resourcefork header.
1395 if (ret == ARCHIVE_OK)
1396 ret = hfs_write_resource_fork_header(a);
1398 * Finish HFS+ Compression.
1399 * - Write the decmpfs xattr.
1400 * - Set the UF_COMPRESSED file flag.
1402 if (ret == ARCHIVE_OK)
1403 ret = hfs_write_decmpfs(a);
1404 if (ret == ARCHIVE_OK)
1405 ret = hfs_set_compressed_fflag(a);
1411 hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1414 const char *buffer_to_write;
1415 size_t bytes_to_write;
1418 if (a->decmpfs_block_count == (unsigned)-1) {
1421 unsigned int block_count;
1423 if (a->decmpfs_header_p == NULL) {
1424 new_block = malloc(MAX_DECMPFS_XATTR_SIZE
1425 + sizeof(uint32_t));
1426 if (new_block == NULL) {
1427 archive_set_error(&a->archive, ENOMEM,
1428 "Can't allocate memory for decmpfs");
1429 return (ARCHIVE_FATAL);
1431 a->decmpfs_header_p = new_block;
1433 a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1434 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1436 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1438 archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1441 /* Calculate a block count of the file. */
1443 (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1444 MAX_DECMPFS_BLOCK_SIZE;
1446 * Allocate buffer for resource fork.
1447 * Set up related pointers;
1450 RSRC_H_SIZE + /* header */
1451 4 + /* Block count */
1452 (block_count * sizeof(uint32_t) * 2) +
1453 RSRC_F_SIZE; /* footer */
1454 if (new_size > a->resource_fork_allocated_size) {
1455 new_block = realloc(a->resource_fork, new_size);
1456 if (new_block == NULL) {
1457 archive_set_error(&a->archive, ENOMEM,
1458 "Can't allocate memory for ResourceFork");
1459 return (ARCHIVE_FATAL);
1461 a->resource_fork_allocated_size = new_size;
1462 a->resource_fork = new_block;
1465 /* Allocate uncompressed buffer */
1466 if (a->uncompressed_buffer == NULL) {
1467 new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
1468 if (new_block == NULL) {
1469 archive_set_error(&a->archive, ENOMEM,
1470 "Can't allocate memory for decmpfs");
1471 return (ARCHIVE_FATAL);
1473 a->uncompressed_buffer = new_block;
1475 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1476 a->file_remaining_bytes = a->filesize;
1477 a->compressed_buffer_remaining = a->compressed_buffer_size;
1480 * Set up a resource fork.
1482 a->rsrc_xattr_options = XATTR_CREATE;
1483 /* Get the position where we are going to set a bunch
1485 a->decmpfs_block_info =
1486 (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1487 /* Set the block count to the resource fork. */
1488 archive_le32enc(a->decmpfs_block_info++, block_count);
1489 /* Get the position where we are going to set compressed
1491 a->compressed_rsrc_position =
1492 RSRC_H_SIZE + 4 + (block_count * 8);
1493 a->compressed_rsrc_position_v = a->compressed_rsrc_position;
1494 a->decmpfs_block_count = block_count;
1497 /* Ignore redundant bytes. */
1498 if (a->file_remaining_bytes == 0)
1499 return ((ssize_t)size);
1501 /* Do not overrun a block size. */
1502 if (size > a->block_remaining_bytes)
1503 bytes_to_write = a->block_remaining_bytes;
1505 bytes_to_write = size;
1506 /* Do not overrun the file size. */
1507 if (bytes_to_write > a->file_remaining_bytes)
1508 bytes_to_write = a->file_remaining_bytes;
1510 /* For efficiency, if a copy length is full of the uncompressed
1511 * buffer size, do not copy writing data to it. */
1512 if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
1513 buffer_to_write = buff;
1515 memcpy(a->uncompressed_buffer +
1516 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
1517 buff, bytes_to_write);
1518 buffer_to_write = a->uncompressed_buffer;
1520 a->block_remaining_bytes -= bytes_to_write;
1521 a->file_remaining_bytes -= bytes_to_write;
1523 if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
1524 ret = hfs_drive_compressor(a, buffer_to_write,
1525 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
1528 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1530 /* Ignore redundant bytes. */
1531 if (a->file_remaining_bytes == 0)
1532 return ((ssize_t)size);
1533 return (bytes_to_write);
1537 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1540 uint64_t start_size = size;
1541 ssize_t bytes_written = 0;
1542 ssize_t bytes_to_write;
1545 return (ARCHIVE_OK);
1547 if (a->filesize == 0 || a->fd < 0) {
1548 archive_set_error(&a->archive, 0,
1549 "Attempt to write to an empty file");
1550 return (ARCHIVE_WARN);
1553 /* If this write would run beyond the file size, truncate it. */
1554 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
1555 start_size = size = (size_t)(a->filesize - a->offset);
1557 /* Write the data. */
1559 bytes_to_write = size;
1560 /* Seek if necessary to the specified offset. */
1561 if (a->offset < a->fd_offset) {
1562 /* Can't support backward move. */
1563 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1565 return (ARCHIVE_FATAL);
1566 } else if (a->offset > a->fd_offset) {
1567 int64_t skip = a->offset - a->fd_offset;
1568 char nullblock[1024];
1570 memset(nullblock, 0, sizeof(nullblock));
1572 if (skip > (int64_t)sizeof(nullblock))
1573 bytes_written = hfs_write_decmpfs_block(
1574 a, nullblock, sizeof(nullblock));
1576 bytes_written = hfs_write_decmpfs_block(
1577 a, nullblock, skip);
1578 if (bytes_written < 0) {
1579 archive_set_error(&a->archive, errno,
1581 return (ARCHIVE_WARN);
1583 skip -= bytes_written;
1586 a->fd_offset = a->offset;
1589 hfs_write_decmpfs_block(a, buff, bytes_to_write);
1590 if (bytes_written < 0)
1591 return (bytes_written);
1592 buff += bytes_written;
1593 size -= bytes_written;
1594 a->total_bytes_written += bytes_written;
1595 a->offset += bytes_written;
1596 a->fd_offset = a->offset;
1598 return (start_size - size);
1602 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1605 return (write_data_block(a, buff, size));
1610 _archive_write_disk_data_block(struct archive *_a,
1611 const void *buff, size_t size, int64_t offset)
1613 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1616 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1617 ARCHIVE_STATE_DATA, "archive_write_data_block");
1620 if (a->todo & TODO_HFS_COMPRESSION)
1621 r = hfs_write_data_block(a, buff, size);
1623 r = write_data_block(a, buff, size);
1626 if ((size_t)r < size) {
1627 archive_set_error(&a->archive, 0,
1628 "Too much data: Truncating file at %ju bytes",
1629 (uintmax_t)a->filesize);
1630 return (ARCHIVE_WARN);
1632 #if ARCHIVE_VERSION_NUMBER < 3999000
1633 return (ARCHIVE_OK);
1640 _archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1642 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1644 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1645 ARCHIVE_STATE_DATA, "archive_write_data");
1647 if (a->todo & TODO_HFS_COMPRESSION)
1648 return (hfs_write_data_block(a, buff, size));
1649 return (write_data_block(a, buff, size));
1653 _archive_write_disk_finish_entry(struct archive *_a)
1655 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1656 int ret = ARCHIVE_OK;
1658 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1659 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1660 "archive_write_finish_entry");
1661 if (a->archive.state & ARCHIVE_STATE_HEADER)
1662 return (ARCHIVE_OK);
1663 archive_clear_error(&a->archive);
1665 /* Pad or truncate file to the right size. */
1667 /* There's no file. */
1668 } else if (a->filesize < 0) {
1669 /* File size is unknown, so we can't set the size. */
1670 } else if (a->fd_offset == a->filesize) {
1671 /* Last write ended at exactly the filesize; we're done. */
1672 /* Hopefully, this is the common case. */
1673 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
1674 } else if (a->todo & TODO_HFS_COMPRESSION) {
1678 if (a->file_remaining_bytes)
1679 memset(null_d, 0, sizeof(null_d));
1680 while (a->file_remaining_bytes) {
1681 if (a->file_remaining_bytes > sizeof(null_d))
1682 r = hfs_write_data_block(
1683 a, null_d, sizeof(null_d));
1685 r = hfs_write_data_block(
1686 a, null_d, a->file_remaining_bytes);
1693 if (ftruncate(a->fd, a->filesize) == -1 &&
1695 archive_set_error(&a->archive, errno,
1696 "File size could not be restored");
1697 return (ARCHIVE_FAILED);
1701 * Not all platforms implement the XSI option to
1702 * extend files via ftruncate. Stat() the file again
1703 * to see what happened.
1706 if ((ret = lazy_stat(a)) != ARCHIVE_OK)
1708 /* We can use lseek()/write() to extend the file if
1709 * ftruncate didn't work or isn't available. */
1710 if (a->st.st_size < a->filesize) {
1711 const char nul = '\0';
1712 if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
1713 archive_set_error(&a->archive, errno,
1715 return (ARCHIVE_FATAL);
1717 if (write(a->fd, &nul, 1) < 0) {
1718 archive_set_error(&a->archive, errno,
1719 "Write to restore size failed");
1720 return (ARCHIVE_FATAL);
1726 /* Restore metadata. */
1729 * This is specific to Mac OS X.
1730 * If the current file is an AppleDouble file, it should be
1731 * linked with the data fork file and remove it.
1733 if (a->todo & TODO_APPLEDOUBLE) {
1734 int r2 = fixup_appledouble(a, a->name);
1735 if (r2 == ARCHIVE_EOF) {
1736 /* The current file has been successfully linked
1737 * with the data fork file and removed. So there
1738 * is nothing to do on the current file. */
1739 goto finish_metadata;
1741 if (r2 < ret) ret = r2;
1745 * Look up the "real" UID only if we're going to need it.
1746 * TODO: the TODO_SGID condition can be dropped here, can't it?
1748 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
1749 a->uid = archive_write_disk_uid(&a->archive,
1750 archive_entry_uname(a->entry),
1751 archive_entry_uid(a->entry));
1753 /* Look up the "real" GID only if we're going to need it. */
1754 /* TODO: the TODO_SUID condition can be dropped here, can't it? */
1755 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
1756 a->gid = archive_write_disk_gid(&a->archive,
1757 archive_entry_gname(a->entry),
1758 archive_entry_gid(a->entry));
1762 * Restore ownership before set_mode tries to restore suid/sgid
1763 * bits. If we set the owner, we know what it is and can skip
1764 * a stat() call to examine the ownership of the file on disk.
1766 if (a->todo & TODO_OWNER) {
1767 int r2 = set_ownership(a);
1768 if (r2 < ret) ret = r2;
1772 * set_mode must precede ACLs on systems such as Solaris and
1773 * FreeBSD where setting the mode implicitly clears extended ACLs
1775 if (a->todo & TODO_MODE) {
1776 int r2 = set_mode(a, a->mode);
1777 if (r2 < ret) ret = r2;
1781 * Security-related extended attributes (such as
1782 * security.capability on Linux) have to be restored last,
1783 * since they're implicitly removed by other file changes.
1785 if (a->todo & TODO_XATTR) {
1786 int r2 = set_xattrs(a);
1787 if (r2 < ret) ret = r2;
1791 * Some flags prevent file modification; they must be restored after
1792 * file contents are written.
1794 if (a->todo & TODO_FFLAGS) {
1795 int r2 = set_fflags(a);
1796 if (r2 < ret) ret = r2;
1800 * Time must follow most other metadata;
1801 * otherwise atime will get changed.
1803 if (a->todo & TODO_TIMES) {
1804 int r2 = set_times_from_entry(a);
1805 if (r2 < ret) ret = r2;
1809 * Mac extended metadata includes ACLs.
1811 if (a->todo & TODO_MAC_METADATA) {
1812 const void *metadata;
1813 size_t metadata_size;
1814 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
1815 if (metadata != NULL && metadata_size > 0) {
1816 int r2 = set_mac_metadata(a, archive_entry_pathname(
1817 a->entry), metadata, metadata_size);
1818 if (r2 < ret) ret = r2;
1823 * ACLs must be restored after timestamps because there are
1824 * ACLs that prevent attribute changes (including time).
1826 if (a->todo & TODO_ACLS) {
1828 r2 = archive_write_disk_set_acls(&a->archive, a->fd,
1829 archive_entry_pathname(a->entry),
1830 archive_entry_acl(a->entry),
1831 archive_entry_mode(a->entry));
1832 if (r2 < ret) ret = r2;
1836 /* If there's an fd, we can close it now. */
1841 if (rename(a->tmpname, a->name) == -1) {
1842 archive_set_error(&a->archive, errno,
1843 "Failed to rename temporary file");
1844 ret = ARCHIVE_FAILED;
1850 /* If there's an entry, we can release it now. */
1851 archive_entry_free(a->entry);
1853 a->archive.state = ARCHIVE_STATE_HEADER;
1858 archive_write_disk_set_group_lookup(struct archive *_a,
1860 la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1861 void (*cleanup_gid)(void *private))
1863 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1864 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1865 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
1867 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1868 (a->cleanup_gid)(a->lookup_gid_data);
1870 a->lookup_gid = lookup_gid;
1871 a->cleanup_gid = cleanup_gid;
1872 a->lookup_gid_data = private_data;
1873 return (ARCHIVE_OK);
1877 archive_write_disk_set_user_lookup(struct archive *_a,
1879 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1880 void (*cleanup_uid)(void *private))
1882 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1883 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1884 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
1886 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1887 (a->cleanup_uid)(a->lookup_uid_data);
1889 a->lookup_uid = lookup_uid;
1890 a->cleanup_uid = cleanup_uid;
1891 a->lookup_uid_data = private_data;
1892 return (ARCHIVE_OK);
1896 archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1898 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1899 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1900 ARCHIVE_STATE_ANY, "archive_write_disk_gid");
1902 return (a->lookup_gid)(a->lookup_gid_data, name, id);
1907 archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1909 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1910 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1911 ARCHIVE_STATE_ANY, "archive_write_disk_uid");
1913 return (a->lookup_uid)(a->lookup_uid_data, name, id);
1918 * Create a new archive_write_disk object and initialize it with global state.
1921 archive_write_disk_new(void)
1923 struct archive_write_disk *a;
1925 a = (struct archive_write_disk *)calloc(1, sizeof(*a));
1928 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
1929 /* We're ready to write a header immediately. */
1930 a->archive.state = ARCHIVE_STATE_HEADER;
1931 a->archive.vtable = archive_write_disk_vtable();
1932 a->start_time = time(NULL);
1933 /* Query and restore the umask. */
1934 umask(a->user_umask = umask(0));
1936 a->user_uid = geteuid();
1937 #endif /* HAVE_GETEUID */
1938 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
1943 a->decmpfs_compression_level = 5;
1945 return (&a->archive);
1950 * If pathname is longer than PATH_MAX, chdir to a suitable
1951 * intermediate dir and edit the path down to a shorter suffix. Note
1952 * that this routine never returns an error; if the chdir() attempt
1953 * fails for any reason, we just go ahead with the long pathname. The
1954 * object creation is likely to fail, but any error will get handled
1957 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
1959 edit_deep_directories(struct archive_write_disk *a)
1962 char *tail = a->name;
1964 /* If path is short, avoid the open() below. */
1965 if (strlen(tail) < PATH_MAX)
1968 /* Try to record our starting dir. */
1969 a->restore_pwd = la_opendirat(AT_FDCWD, ".");
1970 __archive_ensure_cloexec_flag(a->restore_pwd);
1971 if (a->restore_pwd < 0)
1974 /* As long as the path is too long... */
1975 while (strlen(tail) >= PATH_MAX) {
1976 /* Locate a dir prefix shorter than PATH_MAX. */
1977 tail += PATH_MAX - 8;
1978 while (tail > a->name && *tail != '/')
1980 /* Exit if we find a too-long path component. */
1981 if (tail <= a->name)
1983 /* Create the intermediate dir and chdir to it. */
1984 *tail = '\0'; /* Terminate dir portion */
1985 ret = create_dir(a, a->name);
1986 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
1987 ret = ARCHIVE_FAILED;
1988 *tail = '/'; /* Restore the / we removed. */
1989 if (ret != ARCHIVE_OK)
1992 /* The chdir() succeeded; we've now shortened the path. */
2000 * The main restore function.
2003 restore_entry(struct archive_write_disk *a)
2005 int ret = ARCHIVE_OK, en;
2007 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
2009 * TODO: Fix this. Apparently, there are platforms
2010 * that still allow root to hose the entire filesystem
2011 * by unlinking a dir. The S_ISDIR() test above
2012 * prevents us from using unlink() here if the new
2013 * object is a dir, but that doesn't mean the old
2014 * object isn't a dir.
2016 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2017 (void)clear_nochange_fflags(a);
2018 if (unlink(a->name) == 0) {
2019 /* We removed it, reset cached stat. */
2021 } else if (errno == ENOENT) {
2022 /* File didn't exist, that's just as good. */
2023 } else if (rmdir(a->name) == 0) {
2024 /* It was a dir, but now it's gone. */
2027 /* We tried, but couldn't get rid of it. */
2028 archive_set_error(&a->archive, errno,
2029 "Could not unlink");
2030 return(ARCHIVE_FAILED);
2034 /* Try creating it first; if this fails, we'll try to recover. */
2035 en = create_filesystem_object(a);
2037 if ((en == ENOTDIR || en == ENOENT)
2038 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
2039 /* If the parent dir doesn't exist, try creating it. */
2040 create_parent_dir(a, a->name);
2041 /* Now try to create the object again. */
2042 en = create_filesystem_object(a);
2045 if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
2046 archive_set_error(&a->archive, en,
2047 "Hard-link target '%s' does not exist.",
2048 archive_entry_hardlink(a->entry));
2049 return (ARCHIVE_FAILED);
2052 if ((en == EISDIR || en == EEXIST)
2053 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2054 /* If we're not overwriting, we're done. */
2055 if (S_ISDIR(a->mode)) {
2056 /* Don't overwrite any settings on existing directories. */
2059 archive_entry_unset_size(a->entry);
2060 return (ARCHIVE_OK);
2064 * Some platforms return EISDIR if you call
2065 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
2066 * return EEXIST. POSIX is ambiguous, requiring EISDIR
2067 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
2068 * on an existing item.
2071 /* A dir is in the way of a non-dir, rmdir it. */
2072 if (rmdir(a->name) != 0) {
2073 archive_set_error(&a->archive, errno,
2074 "Can't remove already-existing dir");
2075 return (ARCHIVE_FAILED);
2079 en = create_filesystem_object(a);
2080 } else if (en == EEXIST) {
2082 * We know something is in the way, but we don't know what;
2083 * we need to find out before we go any further.
2087 * The SECURE_SYMLINKS logic has already removed a
2088 * symlink to a dir if the client wants that. So
2089 * follow the symlink if we're creating a dir.
2091 if (S_ISDIR(a->mode))
2092 r = la_stat(a->name, &a->st);
2094 * If it's not a dir (or it's a broken symlink),
2095 * then don't follow it.
2097 if (r != 0 || !S_ISDIR(a->mode))
2098 r = lstat(a->name, &a->st);
2100 archive_set_error(&a->archive, errno,
2101 "Can't stat existing object");
2102 return (ARCHIVE_FAILED);
2106 * NO_OVERWRITE_NEWER doesn't apply to directories.
2108 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
2109 && !S_ISDIR(a->st.st_mode)) {
2110 if (!older(&(a->st), a->entry)) {
2111 archive_entry_unset_size(a->entry);
2112 return (ARCHIVE_OK);
2116 /* If it's our archive, we're done. */
2117 if (a->skip_file_set &&
2118 a->st.st_dev == (dev_t)a->skip_file_dev &&
2119 a->st.st_ino == (ino_t)a->skip_file_ino) {
2120 archive_set_error(&a->archive, 0,
2121 "Refusing to overwrite archive");
2122 return (ARCHIVE_FAILED);
2125 if (!S_ISDIR(a->st.st_mode)) {
2126 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2127 (void)clear_nochange_fflags(a);
2129 if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) &&
2130 S_ISREG(a->st.st_mode)) {
2131 /* Use a temporary file to extract */
2132 if ((a->fd = la_mktemp(a)) == -1) {
2133 archive_set_error(&a->archive, errno,
2134 "Can't create temporary file");
2135 return ARCHIVE_FAILED;
2140 /* A non-dir is in the way, unlink it. */
2141 if (unlink(a->name) != 0) {
2142 archive_set_error(&a->archive, errno,
2143 "Can't unlink already-existing "
2145 return (ARCHIVE_FAILED);
2149 en = create_filesystem_object(a);
2151 } else if (!S_ISDIR(a->mode)) {
2152 /* A dir is in the way of a non-dir, rmdir it. */
2153 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2154 (void)clear_nochange_fflags(a);
2155 if (rmdir(a->name) != 0) {
2156 archive_set_error(&a->archive, errno,
2157 "Can't replace existing directory with non-directory");
2158 return (ARCHIVE_FAILED);
2161 en = create_filesystem_object(a);
2164 * There's a dir in the way of a dir. Don't
2165 * waste time with rmdir()/mkdir(), just fix
2166 * up the permissions on the existing dir.
2167 * Note that we don't change perms on existing
2168 * dirs unless _EXTRACT_PERM is specified.
2170 if ((a->mode != a->st.st_mode)
2171 && (a->todo & TODO_MODE_FORCE))
2172 a->deferred |= (a->todo & TODO_MODE);
2173 /* Ownership doesn't need deferred fixup. */
2174 en = 0; /* Forget the EEXIST. */
2179 /* Everything failed; give up here. */
2180 if ((&a->archive)->error == NULL)
2181 archive_set_error(&a->archive, en, "Can't create '%s'",
2183 return (ARCHIVE_FAILED);
2186 a->pst = NULL; /* Cached stat data no longer valid. */
2191 * Returns 0 if creation succeeds, or else returns errno value from
2192 * the failed system call. Note: This function should only ever perform
2193 * a single system call.
2196 create_filesystem_object(struct archive_write_disk *a)
2198 /* Create the entry. */
2199 const char *linkname;
2200 mode_t final_mode, mode;
2202 /* these for check_symlinks_fsobj */
2203 char *linkname_copy; /* non-const copy of linkname */
2205 struct archive_string error_string;
2208 /* We identify hard/symlinks according to the link names. */
2209 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
2210 linkname = archive_entry_hardlink(a->entry);
2211 if (linkname != NULL) {
2215 archive_string_init(&error_string);
2216 linkname_copy = strdup(linkname);
2217 if (linkname_copy == NULL) {
2221 * TODO: consider using the cleaned-up path as the link
2224 r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2225 &error_string, a->flags);
2226 if (r != ARCHIVE_OK) {
2227 archive_set_error(&a->archive, error_number, "%s",
2229 free(linkname_copy);
2230 archive_string_free(&error_string);
2232 * EPERM is more appropriate than error_number for our
2237 r = check_symlinks_fsobj(linkname_copy, &error_number,
2238 &error_string, a->flags);
2239 if (r != ARCHIVE_OK) {
2240 archive_set_error(&a->archive, error_number, "%s",
2242 free(linkname_copy);
2243 archive_string_free(&error_string);
2245 * EPERM is more appropriate than error_number for our
2250 free(linkname_copy);
2251 archive_string_free(&error_string);
2253 * Unlinking and linking here is really not atomic,
2254 * but doing it right, would require us to construct
2255 * an mktemplink() function, and then use rename(2).
2257 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2259 r = link(linkname, a->name) ? errno : 0;
2261 * New cpio and pax formats allow hardlink entries
2262 * to carry data, so we may have to open the file
2263 * for hardlink entries.
2265 * If the hardlink was successfully created and
2266 * the archive doesn't have carry data for it,
2267 * consider it to be non-authoritative for meta data.
2268 * This is consistent with GNU tar and BSD pax.
2269 * If the hardlink does carry data, let the last
2270 * archive entry decide ownership.
2272 if (r == 0 && a->filesize <= 0) {
2275 } else if (r == 0 && a->filesize > 0) {
2277 r = lstat(a->name, &st);
2279 r = la_stat(a->name, &st);
2283 else if ((st.st_mode & AE_IFMT) == AE_IFREG) {
2284 a->fd = open(a->name, O_WRONLY | O_TRUNC |
2285 O_BINARY | O_CLOEXEC | O_NOFOLLOW);
2286 __archive_ensure_cloexec_flag(a->fd);
2294 linkname = archive_entry_symlink(a->entry);
2295 if (linkname != NULL) {
2298 * Unlinking and linking here is really not atomic,
2299 * but doing it right, would require us to construct
2300 * an mktempsymlink() function, and then use rename(2).
2302 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2304 return symlink(linkname, a->name) ? errno : 0;
2311 * The remaining system calls all set permissions, so let's
2312 * try to take advantage of that to avoid an extra chmod()
2313 * call. (Recall that umask is set to zero right now!)
2316 /* Mode we want for the final restored object (w/o file type bits). */
2317 final_mode = a->mode & 07777;
2319 * The mode that will actually be restored in this step. Note
2320 * that SUID, SGID, etc, require additional work to ensure
2321 * security, so we never restore them at this point.
2323 mode = final_mode & 0777 & ~a->user_umask;
2325 switch (a->mode & AE_IFMT) {
2327 /* POSIX requires that we fall through here. */
2331 a->fd = open(a->name,
2332 O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2333 __archive_ensure_cloexec_flag(a->fd);
2338 /* Note: we use AE_IFCHR for the case label, and
2339 * S_IFCHR for the mknod() call. This is correct. */
2340 r = mknod(a->name, mode | S_IFCHR,
2341 archive_entry_rdev(a->entry));
2344 /* TODO: Find a better way to warn about our inability
2345 * to restore a char device node. */
2347 #endif /* HAVE_MKNOD */
2350 r = mknod(a->name, mode | S_IFBLK,
2351 archive_entry_rdev(a->entry));
2354 /* TODO: Find a better way to warn about our inability
2355 * to restore a block device node. */
2357 #endif /* HAVE_MKNOD */
2359 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2360 r = mkdir(a->name, mode);
2362 /* Defer setting dir times. */
2363 a->deferred |= (a->todo & TODO_TIMES);
2364 a->todo &= ~TODO_TIMES;
2365 /* Never use an immediate chmod(). */
2366 /* We can't avoid the chmod() entirely if EXTRACT_PERM
2367 * because of SysV SGID inheritance. */
2368 if ((mode != final_mode)
2369 || (a->flags & ARCHIVE_EXTRACT_PERM))
2370 a->deferred |= (a->todo & TODO_MODE);
2371 a->todo &= ~TODO_MODE;
2376 r = mkfifo(a->name, mode);
2379 /* TODO: Find a better way to warn about our inability
2380 * to restore a fifo. */
2382 #endif /* HAVE_MKFIFO */
2385 /* All the system calls above set errno on failure. */
2389 /* If we managed to set the final mode, we've avoided a chmod(). */
2390 if (mode == final_mode)
2391 a->todo &= ~TODO_MODE;
2396 * Cleanup function for archive_extract. Mostly, this involves processing
2397 * the fixup list, which is used to address a number of problems:
2398 * * Dir permissions might prevent us from restoring a file in that
2399 * dir, so we restore the dir with minimum 0700 permissions first,
2400 * then correct the mode at the end.
2401 * * Similarly, the act of restoring a file touches the directory
2402 * and changes the timestamp on the dir, so we have to touch-up dir
2403 * timestamps at the end as well.
2404 * * Some file flags can interfere with the restore by, for example,
2405 * preventing the creation of hardlinks to those files.
2406 * * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2408 * Note that tar/cpio do not require that archives be in a particular
2409 * order; there is no way to know when the last file has been restored
2410 * within a directory, so there's no way to optimize the memory usage
2411 * here by fixing up the directory any earlier than the
2414 * XXX TODO: Directory ACLs should be restored here, for the same
2415 * reason we set directory perms here. XXX
2418 _archive_write_disk_close(struct archive *_a)
2420 struct archive_write_disk *a = (struct archive_write_disk *)_a;
2421 struct fixup_entry *next, *p;
2424 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2425 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2426 "archive_write_disk_close");
2427 ret = _archive_write_disk_finish_entry(&a->archive);
2429 /* Sort dir list so directories are fixed up in depth-first order. */
2430 p = sort_dir_list(a->fixup_list);
2434 a->pst = NULL; /* Mark stat cache as out-of-date. */
2436 (TODO_TIMES | TODO_MODE_BASE | TODO_ACLS | TODO_FFLAGS)) {
2438 O_WRONLY | O_BINARY | O_NOFOLLOW | O_CLOEXEC);
2440 if (p->fixup & TODO_TIMES) {
2441 set_times(a, fd, p->mode, p->name,
2442 p->atime, p->atime_nanos,
2443 p->birthtime, p->birthtime_nanos,
2444 p->mtime, p->mtime_nanos,
2445 p->ctime, p->ctime_nanos);
2447 if (p->fixup & TODO_MODE_BASE) {
2450 fchmod(fd, p->mode);
2453 chmod(p->name, p->mode);
2455 if (p->fixup & TODO_ACLS)
2456 archive_write_disk_set_acls(&a->archive, fd,
2457 p->name, &p->acl, p->mode);
2458 if (p->fixup & TODO_FFLAGS)
2459 set_fflags_platform(a, fd, p->name,
2460 p->mode, p->fflags_set, 0);
2461 if (p->fixup & TODO_MAC_METADATA)
2462 set_mac_metadata(a, p->name, p->mac_metadata,
2463 p->mac_metadata_size);
2465 archive_acl_clear(&p->acl);
2466 free(p->mac_metadata);
2473 a->fixup_list = NULL;
2478 _archive_write_disk_free(struct archive *_a)
2480 struct archive_write_disk *a;
2483 return (ARCHIVE_OK);
2484 archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2485 ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2486 a = (struct archive_write_disk *)_a;
2487 ret = _archive_write_disk_close(&a->archive);
2488 archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2489 archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2490 archive_entry_free(a->entry);
2491 archive_string_free(&a->_name_data);
2492 archive_string_free(&a->_tmpname_data);
2493 archive_string_free(&a->archive.error_string);
2494 archive_string_free(&a->path_safe);
2495 a->archive.magic = 0;
2496 __archive_clean(&a->archive);
2497 free(a->decmpfs_header_p);
2498 free(a->resource_fork);
2499 free(a->compressed_buffer);
2500 free(a->uncompressed_buffer);
2501 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2502 && defined(HAVE_ZLIB_H)
2503 if (a->stream_valid) {
2504 switch (deflateEnd(&a->stream)) {
2508 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2509 "Failed to clean up compressor");
2510 ret = ARCHIVE_FATAL;
2520 * Simple O(n log n) merge sort to order the fixup list. In
2521 * particular, we want to restore dir timestamps depth-first.
2523 static struct fixup_entry *
2524 sort_dir_list(struct fixup_entry *p)
2526 struct fixup_entry *a, *b, *t;
2530 /* A one-item list is already sorted. */
2531 if (p->next == NULL)
2534 /* Step 1: split the list. */
2538 /* Step a twice, t once. */
2544 /* Now, t is at the mid-point, so break the list here. */
2549 /* Step 2: Recursively sort the two sub-lists. */
2550 a = sort_dir_list(a);
2551 b = sort_dir_list(b);
2553 /* Step 3: Merge the returned lists. */
2554 /* Pick the first element for the merged list. */
2555 if (strcmp(a->name, b->name) > 0) {
2563 /* Always put the later element on the list first. */
2564 while (a != NULL && b != NULL) {
2565 if (strcmp(a->name, b->name) > 0) {
2575 /* Only one list is non-empty, so just splice it on. */
2585 * Returns a new, initialized fixup entry.
2587 * TODO: Reduce the memory requirements for this list by using a tree
2588 * structure rather than a simple list of names.
2590 static struct fixup_entry *
2591 new_fixup(struct archive_write_disk *a, const char *pathname)
2593 struct fixup_entry *fe;
2595 fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2597 archive_set_error(&a->archive, ENOMEM,
2598 "Can't allocate memory for a fixup");
2601 fe->next = a->fixup_list;
2604 fe->name = strdup(pathname);
2609 * Returns a fixup structure for the current entry.
2611 static struct fixup_entry *
2612 current_fixup(struct archive_write_disk *a, const char *pathname)
2614 if (a->current_fixup == NULL)
2615 a->current_fixup = new_fixup(a, pathname);
2616 return (a->current_fixup);
2619 /* Error helper for new *_fsobj functions */
2621 fsobj_error(int *a_eno, struct archive_string *a_estr,
2622 int err, const char *errstr, const char *path)
2627 archive_string_sprintf(a_estr, "%s%s", errstr, path);
2631 * TODO: Someday, integrate this with the deep dir support; they both
2632 * scan the path and both can be optimized by comparing against other
2636 * Checks the given path to see if any elements along it are symlinks. Returns
2637 * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2640 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2643 #if !defined(HAVE_LSTAT) && \
2644 !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT))
2645 /* Platform doesn't have lstat, so we can't look for symlinks. */
2646 (void)path; /* UNUSED */
2647 (void)error_number; /* UNUSED */
2648 (void)error_string; /* UNUSED */
2649 (void)flags; /* UNUSED */
2650 return (ARCHIVE_OK);
2652 int res = ARCHIVE_OK;
2660 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2664 /* Nothing to do here if name is empty */
2666 return (ARCHIVE_OK);
2669 * Guard against symlink tricks. Reject any archive entry whose
2670 * destination would be altered by a symlink.
2672 * Walk the filename in chunks separated by '/'. For each segment:
2673 * - if it doesn't exist, continue
2674 * - if it's symlink, abort or remove it
2675 * - if it's a directory and it's not the last chunk, cd into it
2677 * head points to the current (relative) path
2678 * tail points to the temporary \0 terminating the segment we're
2679 * currently examining
2680 * c holds what used to be in *tail
2681 * last is 1 if this is the last tail
2683 chdir_fd = la_opendirat(AT_FDCWD, ".");
2684 __archive_ensure_cloexec_flag(chdir_fd);
2686 fsobj_error(a_eno, a_estr, errno,
2687 "Could not open ", path);
2688 return (ARCHIVE_FATAL);
2693 /* TODO: reintroduce a safe cache here? */
2694 /* Skip the root directory if the path is absolute. */
2695 if(tail == path && tail[0] == '/')
2697 /* Keep going until we've checked the entire name.
2698 * head, tail, path all alias the same string, which is
2699 * temporarily zeroed at tail, so be careful restoring the
2700 * stashed (c=tail[0]) for error messages.
2701 * Exiting the loop with break is okay; continue is not.
2705 * Skip the separator we just consumed, plus any adjacent ones
2707 while (*tail == '/')
2709 /* Skip the next path element. */
2710 while (*tail != '\0' && *tail != '/')
2712 /* is this the last path component? */
2713 last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2714 /* temporarily truncate the string here */
2717 /* Check that we haven't hit a symlink. */
2718 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2719 r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW);
2721 r = lstat(head, &st);
2725 /* We've hit a dir that doesn't exist; stop now. */
2726 if (errno == ENOENT) {
2730 * Treat any other error as fatal - best to be
2732 * Note: This effectively disables deep
2733 * directory support when security checks are
2734 * enabled. Otherwise, very long pathnames that
2735 * trigger an error here could evade the
2737 * TODO: We could do better, but it would
2738 * probably require merging the symlink checks
2739 * with the deep-directory editing.
2741 fsobj_error(a_eno, a_estr, errno,
2742 "Could not stat ", path);
2743 res = ARCHIVE_FAILED;
2746 } else if (S_ISDIR(st.st_mode)) {
2748 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2749 fd = la_opendirat(chdir_fd, head);
2762 fsobj_error(a_eno, a_estr, errno,
2763 "Could not chdir ", path);
2764 res = (ARCHIVE_FATAL);
2767 /* Our view is now from inside this dir: */
2770 } else if (S_ISLNK(st.st_mode)) {
2773 * Last element is symlink; remove it
2774 * so we can overwrite it with the
2775 * item being extracted.
2777 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2778 r = unlinkat(chdir_fd, head, 0);
2784 fsobj_error(a_eno, a_estr, errno,
2785 "Could not remove symlink ",
2787 res = ARCHIVE_FAILED;
2791 * Even if we did remove it, a warning
2792 * is in order. The warning is silly,
2793 * though, if we're just replacing one
2794 * symlink with another symlink.
2798 * FIXME: not sure how important this is to
2802 if (!S_ISLNK(path)) {
2803 fsobj_error(a_eno, a_estr, 0,
2804 "Removing symlink ", path);
2807 /* Symlink gone. No more problem! */
2810 } else if (flags & ARCHIVE_EXTRACT_UNLINK) {
2811 /* User asked us to remove problems. */
2812 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2813 r = unlinkat(chdir_fd, head, 0);
2819 fsobj_error(a_eno, a_estr, 0,
2820 "Cannot remove intervening "
2822 res = ARCHIVE_FAILED;
2827 ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
2829 * We are not the last element and we want to
2830 * follow symlinks if they are a directory.
2832 * This is needed to extract hardlinks over
2835 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2836 r = fstatat(chdir_fd, head, &st, 0);
2838 r = la_stat(head, &st);
2842 if (errno == ENOENT) {
2845 fsobj_error(a_eno, a_estr,
2847 "Could not stat ", path);
2848 res = (ARCHIVE_FAILED);
2851 } else if (S_ISDIR(st.st_mode)) {
2852 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2853 fd = la_opendirat(chdir_fd, head);
2866 fsobj_error(a_eno, a_estr,
2868 "Could not chdir ", path);
2869 res = (ARCHIVE_FATAL);
2873 * Our view is now from inside
2879 fsobj_error(a_eno, a_estr, 0,
2880 "Cannot extract through "
2882 res = ARCHIVE_FAILED;
2887 fsobj_error(a_eno, a_estr, 0,
2888 "Cannot extract through symlink ", path);
2889 res = ARCHIVE_FAILED;
2893 /* be sure to always maintain this */
2895 if (tail[0] != '\0')
2896 tail++; /* Advance to the next segment. */
2898 /* Catches loop exits via break */
2900 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2901 /* If we operate with openat(), fstatat() and unlinkat() there was
2902 * no chdir(), so just close the fd */
2906 /* If we changed directory above, restore it here. */
2907 if (chdir_fd >= 0) {
2908 r = fchdir(chdir_fd);
2910 fsobj_error(a_eno, a_estr, errno,
2911 "chdir() failure", "");
2916 res = (ARCHIVE_FATAL);
2920 /* TODO: reintroduce a safe cache here? */
2926 * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
2927 * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
2930 check_symlinks(struct archive_write_disk *a)
2932 struct archive_string error_string;
2935 archive_string_init(&error_string);
2936 rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
2938 if (rc != ARCHIVE_OK) {
2939 archive_set_error(&a->archive, error_number, "%s",
2942 archive_string_free(&error_string);
2943 a->pst = NULL; /* to be safe */
2948 #if defined(__CYGWIN__)
2950 * 1. Convert a path separator from '\' to '/' .
2951 * We shouldn't check multibyte character directly because some
2952 * character-set have been using the '\' character for a part of
2953 * its multibyte character code.
2954 * 2. Replace unusable characters in Windows with underscore('_').
2955 * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
2958 cleanup_pathname_win(char *path)
2963 int mb, complete, utf8;
2968 utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
2969 for (p = path; *p != '\0'; p++) {
2972 /* If previous byte is smaller than 128,
2973 * this is not second byte of multibyte characters,
2974 * so we can replace '\' with '/'. */
2978 complete = 0;/* uncompleted. */
2979 } else if (*(unsigned char *)p > 127)
2983 /* Rewrite the path name if its next character is unusable. */
2984 if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
2985 *p == '<' || *p == '>' || *p == '|')
2992 * Convert path separator in wide-character.
2995 while (*p != '\0' && alen) {
2996 l = mbtowc(&wc, p, alen);
2997 if (l == (size_t)-1) {
2998 while (*p != '\0') {
3005 if (l == 1 && wc == L'\\')
3014 * Canonicalize the pathname. In particular, this strips duplicate
3015 * '/' characters, '.' elements, and trailing '/'. It also raises an
3016 * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
3017 * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
3018 * is set) if the path is absolute.
3021 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
3025 char separator = '\0';
3029 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3030 "Invalid empty ", "pathname");
3031 return (ARCHIVE_FAILED);
3034 #if defined(__CYGWIN__)
3035 cleanup_pathname_win(path);
3037 /* Skip leading '/'. */
3039 if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
3040 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3041 "Path is ", "absolute");
3042 return (ARCHIVE_FAILED);
3048 /* Scan the pathname one element at a time. */
3050 /* src points to first char after '/' */
3051 if (src[0] == '\0') {
3053 } else if (src[0] == '/') {
3054 /* Found '//', ignore second one. */
3057 } else if (src[0] == '.') {
3058 if (src[1] == '\0') {
3059 /* Ignore trailing '.' */
3061 } else if (src[1] == '/') {
3065 } else if (src[1] == '.') {
3066 if (src[2] == '/' || src[2] == '\0') {
3067 /* Conditionally warn about '..' */
3069 & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3070 fsobj_error(a_eno, a_estr,
3072 "Path contains ", "'..'");
3073 return (ARCHIVE_FAILED);
3077 * Note: Under no circumstances do we
3078 * remove '..' elements. In
3079 * particular, restoring
3080 * '/foo/../bar/' should create the
3081 * 'foo' dir as a side-effect.
3086 /* Copy current element, including leading '/'. */
3089 while (*src != '\0' && *src != '/') {
3096 /* Skip '/' separator. */
3100 * We've just copied zero or more path elements, not including the
3105 * Nothing got copied. The path must have been something
3106 * like '.' or '/' or './' or '/././././/./'.
3113 /* Terminate the result. */
3115 return (ARCHIVE_OK);
3119 cleanup_pathname(struct archive_write_disk *a)
3121 struct archive_string error_string;
3124 archive_string_init(&error_string);
3125 rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3127 if (rc != ARCHIVE_OK) {
3128 archive_set_error(&a->archive, error_number, "%s",
3131 archive_string_free(&error_string);
3136 * Create the parent directory of the specified path, assuming path
3137 * is already in mutable storage.
3140 create_parent_dir(struct archive_write_disk *a, char *path)
3145 /* Remove tail element to obtain parent name. */
3146 slash = strrchr(path, '/');
3148 return (ARCHIVE_OK);
3150 r = create_dir(a, path);
3156 * Create the specified dir, recursing to create parents as necessary.
3158 * Returns ARCHIVE_OK if the path exists when we're done here.
3159 * Otherwise, returns ARCHIVE_FAILED.
3160 * Assumes path is in mutable storage; path is unchanged on exit.
3163 create_dir(struct archive_write_disk *a, char *path)
3166 struct fixup_entry *le;
3168 mode_t mode_final, mode;
3171 /* Check for special names and just skip them. */
3172 slash = strrchr(path, '/');
3178 if (base[0] == '\0' ||
3179 (base[0] == '.' && base[1] == '\0') ||
3180 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
3181 /* Don't bother trying to create null path, '.', or '..'. */
3182 if (slash != NULL) {
3184 r = create_dir(a, path);
3188 return (ARCHIVE_OK);
3192 * Yes, this should be stat() and not lstat(). Using lstat()
3193 * here loses the ability to extract through symlinks. Also note
3194 * that this should not use the a->st cache.
3196 if (la_stat(path, &st) == 0) {
3197 if (S_ISDIR(st.st_mode))
3198 return (ARCHIVE_OK);
3199 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
3200 archive_set_error(&a->archive, EEXIST,
3201 "Can't create directory '%s'", path);
3202 return (ARCHIVE_FAILED);
3204 if (unlink(path) != 0) {
3205 archive_set_error(&a->archive, errno,
3206 "Can't create directory '%s': "
3207 "Conflicting file cannot be removed",
3209 return (ARCHIVE_FAILED);
3211 } else if (errno != ENOENT && errno != ENOTDIR) {
3213 archive_set_error(&a->archive, errno,
3214 "Can't test directory '%s'", path);
3215 return (ARCHIVE_FAILED);
3216 } else if (slash != NULL) {
3218 r = create_dir(a, path);
3220 if (r != ARCHIVE_OK)
3225 * Mode we want for the final restored directory. Per POSIX,
3226 * implicitly-created dirs must be created obeying the umask.
3227 * There's no mention whether this is different for privileged
3228 * restores (which the rest of this code handles by pretending
3229 * umask=0). I've chosen here to always obey the user's umask for
3230 * implicit dirs, even if _EXTRACT_PERM was specified.
3232 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3233 /* Mode we want on disk during the restore process. */
3235 mode |= MINIMUM_DIR_MODE;
3236 mode &= MAXIMUM_DIR_MODE;
3237 if (mkdir(path, mode) == 0) {
3238 if (mode != mode_final) {
3239 le = new_fixup(a, path);
3241 return (ARCHIVE_FATAL);
3242 le->fixup |=TODO_MODE_BASE;
3243 le->mode = mode_final;
3245 return (ARCHIVE_OK);
3249 * Without the following check, a/b/../b/c/d fails at the
3250 * second visit to 'b', so 'd' can't be created. Note that we
3251 * don't add it to the fixup list here, as it's already been
3254 if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3255 return (ARCHIVE_OK);
3257 archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3259 return (ARCHIVE_FAILED);
3263 * Note: Although we can skip setting the user id if the desired user
3264 * id matches the current user, we cannot skip setting the group, as
3265 * many systems set the gid based on the containing directory. So
3266 * we have to perform a chown syscall if we want to set the SGID
3267 * bit. (The alternative is to stat() and then possibly chown(); it's
3268 * more efficient to skip the stat() and just always chown().) Note
3269 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3270 * allows set_mode to skip the stat() check for the GID.
3273 set_ownership(struct archive_write_disk *a)
3275 #if !defined(__CYGWIN__) && !defined(__linux__)
3277 * On Linux, a process may have the CAP_CHOWN capability.
3278 * On Windows there is no 'root' user with uid 0.
3279 * Elsewhere we can skip calling chown if we are not root and the desired
3280 * user id does not match the current user.
3282 if (a->user_uid != 0 && a->user_uid != a->uid) {
3283 archive_set_error(&a->archive, errno,
3284 "Can't set UID=%jd", (intmax_t)a->uid);
3285 return (ARCHIVE_WARN);
3290 /* If we have an fd, we can avoid a race. */
3291 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3292 /* We've set owner and know uid/gid are correct. */
3293 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3294 return (ARCHIVE_OK);
3298 /* We prefer lchown() but will use chown() if that's all we have. */
3299 /* Of course, if we have neither, this will always fail. */
3301 if (lchown(a->name, a->uid, a->gid) == 0) {
3302 /* We've set owner and know uid/gid are correct. */
3303 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3304 return (ARCHIVE_OK);
3307 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3308 /* We've set owner and know uid/gid are correct. */
3309 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3310 return (ARCHIVE_OK);
3314 archive_set_error(&a->archive, errno,
3315 "Can't set user=%jd/group=%jd for %s",
3316 (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3317 return (ARCHIVE_WARN);
3321 * Note: Returns 0 on success, non-zero on failure.
3324 set_time(int fd, int mode, const char *name,
3325 time_t atime, long atime_nsec,
3326 time_t mtime, long mtime_nsec)
3328 /* Select the best implementation for this platform. */
3329 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3331 * utimensat() and futimens() are defined in
3332 * POSIX.1-2008. They support ns resolution and setting times
3333 * on fds and symlinks.
3335 struct timespec ts[2];
3336 (void)mode; /* UNUSED */
3337 ts[0].tv_sec = atime;
3338 ts[0].tv_nsec = atime_nsec;
3339 ts[1].tv_sec = mtime;
3340 ts[1].tv_nsec = mtime_nsec;
3342 return futimens(fd, ts);
3343 return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3347 * The utimes()-family functions support µs-resolution and
3348 * setting times fds and symlinks. utimes() is documented as
3349 * LEGACY by POSIX, futimes() and lutimes() are not described
3352 struct timeval times[2];
3354 times[0].tv_sec = atime;
3355 times[0].tv_usec = atime_nsec / 1000;
3356 times[1].tv_sec = mtime;
3357 times[1].tv_usec = mtime_nsec / 1000;
3361 return (futimes(fd, times));
3363 (void)fd; /* UNUSED */
3366 (void)mode; /* UNUSED */
3367 return (lutimes(name, times));
3371 return (utimes(name, times));
3374 #elif defined(HAVE_UTIME)
3376 * utime() is POSIX-standard but only supports 1s resolution and
3377 * does not support fds or symlinks.
3379 struct utimbuf times;
3380 (void)fd; /* UNUSED */
3381 (void)name; /* UNUSED */
3382 (void)atime_nsec; /* UNUSED */
3383 (void)mtime_nsec; /* UNUSED */
3384 times.actime = atime;
3385 times.modtime = mtime;
3387 return (ARCHIVE_OK);
3388 return (utime(name, ×));
3392 * We don't know how to set the time on this platform.
3394 (void)fd; /* UNUSED */
3395 (void)mode; /* UNUSED */
3396 (void)name; /* UNUSED */
3397 (void)atime_nsec; /* UNUSED */
3398 (void)mtime_nsec; /* UNUSED */
3399 return (ARCHIVE_WARN);
3405 set_time_tru64(int fd, int mode, const char *name,
3406 time_t atime, long atime_nsec,
3407 time_t mtime, long mtime_nsec,
3408 time_t ctime, long ctime_nsec)
3410 struct attr_timbuf tstamp;
3411 tstamp.atime.tv_sec = atime;
3412 tstamp.mtime.tv_sec = mtime;
3413 tstamp.ctime.tv_sec = ctime;
3414 #if defined (__hpux) && defined (__ia64)
3415 tstamp.atime.tv_nsec = atime_nsec;
3416 tstamp.mtime.tv_nsec = mtime_nsec;
3417 tstamp.ctime.tv_nsec = ctime_nsec;
3419 tstamp.atime.tv_usec = atime_nsec / 1000;
3420 tstamp.mtime.tv_usec = mtime_nsec / 1000;
3421 tstamp.ctime.tv_usec = ctime_nsec / 1000;
3423 return (fcntl(fd,F_SETTIMES,&tstamp));
3425 #endif /* F_SETTIMES */
3428 set_times(struct archive_write_disk *a,
3429 int fd, int mode, const char *name,
3430 time_t atime, long atime_nanos,
3431 time_t birthtime, long birthtime_nanos,
3432 time_t mtime, long mtime_nanos,
3433 time_t cctime, long ctime_nanos)
3435 /* Note: set_time doesn't use libarchive return conventions!
3436 * It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */
3441 * on Tru64 try own fcntl first which can restore even the
3442 * ctime, fall back to default code path below if it fails
3443 * or if we are not running as root
3445 if (a->user_uid == 0 &&
3446 set_time_tru64(fd, mode, name,
3447 atime, atime_nanos, mtime,
3448 mtime_nanos, cctime, ctime_nanos) == 0) {
3449 return (ARCHIVE_OK);
3452 (void)cctime; /* UNUSED */
3453 (void)ctime_nanos; /* UNUSED */
3456 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3458 * If you have struct stat.st_birthtime, we assume BSD
3459 * birthtime semantics, in which {f,l,}utimes() updates
3460 * birthtime to earliest mtime. So we set the time twice,
3461 * first using the birthtime, then using the mtime. If
3462 * birthtime == mtime, this isn't necessary, so we skip it.
3463 * If birthtime > mtime, then this won't work, so we skip it.
3465 if (birthtime < mtime
3466 || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3467 r1 = set_time(fd, mode, name,
3469 birthtime, birthtime_nanos);
3471 (void)birthtime; /* UNUSED */
3472 (void)birthtime_nanos; /* UNUSED */
3474 r2 = set_time(fd, mode, name,
3476 mtime, mtime_nanos);
3477 if (r1 != 0 || r2 != 0) {
3478 archive_set_error(&a->archive, errno,
3479 "Can't restore time");
3480 return (ARCHIVE_WARN);
3482 return (ARCHIVE_OK);
3486 set_times_from_entry(struct archive_write_disk *a)
3488 time_t atime, birthtime, mtime, cctime;
3489 long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3491 /* Suitable defaults. */
3492 atime = birthtime = mtime = cctime = a->start_time;
3493 atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3495 /* If no time was provided, we're done. */
3496 if (!archive_entry_atime_is_set(a->entry)
3497 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
3498 && !archive_entry_birthtime_is_set(a->entry)
3500 && !archive_entry_mtime_is_set(a->entry))
3501 return (ARCHIVE_OK);
3503 if (archive_entry_atime_is_set(a->entry)) {
3504 atime = archive_entry_atime(a->entry);
3505 atime_nsec = archive_entry_atime_nsec(a->entry);
3507 if (archive_entry_birthtime_is_set(a->entry)) {
3508 birthtime = archive_entry_birthtime(a->entry);
3509 birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3511 if (archive_entry_mtime_is_set(a->entry)) {
3512 mtime = archive_entry_mtime(a->entry);
3513 mtime_nsec = archive_entry_mtime_nsec(a->entry);
3515 if (archive_entry_ctime_is_set(a->entry)) {
3516 cctime = archive_entry_ctime(a->entry);
3517 ctime_nsec = archive_entry_ctime_nsec(a->entry);
3520 return set_times(a, a->fd, a->mode, a->name,
3522 birthtime, birthtime_nsec,
3524 cctime, ctime_nsec);
3528 set_mode(struct archive_write_disk *a, int mode)
3532 mode &= 07777; /* Strip off file type bits. */
3534 if (a->todo & TODO_SGID_CHECK) {
3536 * If we don't know the GID is right, we must stat()
3537 * to verify it. We can't just check the GID of this
3538 * process, since systems sometimes set GID from
3539 * the enclosing dir or based on ACLs.
3541 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3543 if (a->pst->st_gid != a->gid) {
3545 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3547 * This is only an error if you
3548 * requested owner restore. If you
3549 * didn't, we'll try to restore
3550 * sgid/suid, but won't consider it a
3551 * problem if we can't.
3553 archive_set_error(&a->archive, -1,
3554 "Can't restore SGID bit");
3558 /* While we're here, double-check the UID. */
3559 if (a->pst->st_uid != a->uid
3560 && (a->todo & TODO_SUID)) {
3562 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3563 archive_set_error(&a->archive, -1,
3564 "Can't restore SUID bit");
3568 a->todo &= ~TODO_SGID_CHECK;
3569 a->todo &= ~TODO_SUID_CHECK;
3570 } else if (a->todo & TODO_SUID_CHECK) {
3572 * If we don't know the UID is right, we can just check
3573 * the user, since all systems set the file UID from
3576 if (a->user_uid != a->uid) {
3578 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3579 archive_set_error(&a->archive, -1,
3580 "Can't make file SUID");
3584 a->todo &= ~TODO_SUID_CHECK;
3587 if (S_ISLNK(a->mode)) {
3590 * If this is a symlink, use lchmod(). If the
3591 * platform doesn't support lchmod(), just skip it. A
3592 * platform that doesn't provide a way to set
3593 * permissions on symlinks probably ignores
3594 * permissions on symlinks, so a failure here has no
3597 if (lchmod(a->name, mode) != 0) {
3601 #if ENOTSUP != EOPNOTSUPP
3605 * if lchmod is defined but the platform
3606 * doesn't support it, silently ignore
3611 archive_set_error(&a->archive, errno,
3612 "Can't set permissions to 0%o", (int)mode);
3617 } else if (!S_ISDIR(a->mode)) {
3619 * If it's not a symlink and not a dir, then use
3620 * fchmod() or chmod(), depending on whether we have
3621 * an fd. Dirs get their perms set during the
3622 * post-extract fixup, which is handled elsewhere.
3626 r2 = fchmod(a->fd, mode);
3629 /* If this platform lacks fchmod(), then
3630 * we'll just use chmod(). */
3631 r2 = chmod(a->name, mode);
3634 archive_set_error(&a->archive, errno,
3635 "Can't set permissions to 0%o", (int)mode);
3643 set_fflags(struct archive_write_disk *a)
3645 struct fixup_entry *le;
3646 unsigned long set, clear;
3648 mode_t mode = archive_entry_mode(a->entry);
3650 * Make 'critical_flags' hold all file flags that can't be
3651 * immediately restored. For example, on BSD systems,
3652 * SF_IMMUTABLE prevents hardlinks from being created, so
3653 * should not be set until after any hardlinks are created. To
3654 * preserve some semblance of portability, this uses #ifdef
3655 * extensively. Ugly, but it works.
3657 * Yes, Virginia, this does create a security race. It's mitigated
3658 * somewhat by the practice of creating dirs 0700 until the extract
3659 * is done, but it would be nice if we could do more than that.
3660 * People restoring critical file systems should be wary of
3661 * other programs that might try to muck with files as they're
3664 const int critical_flags = 0
3677 #if defined(FS_APPEND_FL)
3679 #elif defined(EXT2_APPEND_FL)
3682 #if defined(FS_IMMUTABLE_FL)
3684 #elif defined(EXT2_IMMUTABLE_FL)
3687 #ifdef FS_JOURNAL_DATA_FL
3688 | FS_JOURNAL_DATA_FL
3692 if (a->todo & TODO_FFLAGS) {
3693 archive_entry_fflags(a->entry, &set, &clear);
3696 * The first test encourages the compiler to eliminate
3697 * all of this if it's not necessary.
3699 if ((critical_flags != 0) && (set & critical_flags)) {
3700 le = current_fixup(a, a->name);
3702 return (ARCHIVE_FATAL);
3703 le->fixup |= TODO_FFLAGS;
3704 le->fflags_set = set;
3705 /* Store the mode if it's not already there. */
3706 if ((le->fixup & TODO_MODE) == 0)
3709 r = set_fflags_platform(a, a->fd,
3710 a->name, mode, set, clear);
3711 if (r != ARCHIVE_OK)
3715 return (ARCHIVE_OK);
3719 clear_nochange_fflags(struct archive_write_disk *a)
3721 mode_t mode = archive_entry_mode(a->entry);
3722 const int nochange_flags = 0
3735 #ifdef EXT2_APPEND_FL
3738 #ifdef EXT2_IMMUTABLE_FL
3743 return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3748 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3750 * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3753 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3754 mode_t mode, unsigned long set, unsigned long clear)
3757 const int sf_mask = 0
3771 (void)mode; /* UNUSED */
3773 if (set == 0 && clear == 0)
3774 return (ARCHIVE_OK);
3777 * XXX Is the stat here really necessary? Or can I just use
3778 * the 'set' flags directly? In particular, I'm not sure
3779 * about the correct approach if we're overwriting an existing
3780 * file that already has flags on it. XXX
3782 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3785 a->st.st_flags &= ~clear;
3786 a->st.st_flags |= set;
3788 /* Only super-user may change SF_* flags */
3790 if (a->user_uid != 0)
3791 a->st.st_flags &= ~sf_mask;
3793 #ifdef HAVE_FCHFLAGS
3794 /* If platform has fchflags() and we were given an fd, use it. */
3795 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
3796 return (ARCHIVE_OK);
3799 * If we can't use the fd to set the flags, we'll use the
3800 * pathname to set flags. We prefer lchflags() but will use
3801 * chflags() if we must.
3803 #ifdef HAVE_LCHFLAGS
3804 if (lchflags(name, a->st.st_flags) == 0)
3805 return (ARCHIVE_OK);
3806 #elif defined(HAVE_CHFLAGS)
3807 if (S_ISLNK(a->st.st_mode)) {
3808 archive_set_error(&a->archive, errno,
3809 "Can't set file flags on symlink.");
3810 return (ARCHIVE_WARN);
3812 if (chflags(name, a->st.st_flags) == 0)
3813 return (ARCHIVE_OK);
3815 archive_set_error(&a->archive, errno,
3816 "Failed to set file flags");
3817 return (ARCHIVE_WARN);
3820 #elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \
3821 defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
3822 (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \
3823 defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
3825 * Linux uses ioctl() to read and write file flags.
3828 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3829 mode_t mode, unsigned long set, unsigned long clear)
3833 int newflags, oldflags;
3835 * Linux has no define for the flags that are only settable by
3836 * the root user. This code may seem a little complex, but
3837 * there seem to be some Linux systems that lack these
3838 * defines. (?) The code below degrades reasonably gracefully
3839 * if sf_mask is incomplete.
3841 const int sf_mask = 0
3842 #if defined(FS_IMMUTABLE_FL)
3844 #elif defined(EXT2_IMMUTABLE_FL)
3847 #if defined(FS_APPEND_FL)
3849 #elif defined(EXT2_APPEND_FL)
3852 #if defined(FS_JOURNAL_DATA_FL)
3853 | FS_JOURNAL_DATA_FL
3857 if (set == 0 && clear == 0)
3858 return (ARCHIVE_OK);
3859 /* Only regular files and dirs can have flags. */
3860 if (!S_ISREG(mode) && !S_ISDIR(mode))
3861 return (ARCHIVE_OK);
3863 /* If we weren't given an fd, open it ourselves. */
3865 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
3866 __archive_ensure_cloexec_flag(myfd);
3869 return (ARCHIVE_OK);
3872 * XXX As above, this would be way simpler if we didn't have
3873 * to read the current flags from disk. XXX
3877 /* Read the current file flags. */
3879 #ifdef FS_IOC_GETFLAGS
3887 /* Try setting the flags as given. */
3888 newflags = (oldflags & ~clear) | set;
3890 #ifdef FS_IOC_SETFLAGS
3900 /* If we couldn't set all the flags, try again with a subset. */
3901 newflags &= ~sf_mask;
3902 oldflags &= sf_mask;
3903 newflags |= oldflags;
3905 #ifdef FS_IOC_SETFLAGS
3913 /* We couldn't set the flags, so report the failure. */
3915 archive_set_error(&a->archive, errno,
3916 "Failed to set file flags");
3927 * Of course, some systems have neither BSD chflags() nor Linux' flags
3928 * support through ioctl().
3931 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3932 mode_t mode, unsigned long set, unsigned long clear)
3934 (void)a; /* UNUSED */
3935 (void)fd; /* UNUSED */
3936 (void)name; /* UNUSED */
3937 (void)mode; /* UNUSED */
3938 (void)set; /* UNUSED */
3939 (void)clear; /* UNUSED */
3940 return (ARCHIVE_OK);
3943 #endif /* __linux */
3945 #ifndef HAVE_COPYFILE_H
3946 /* Default is to simply drop Mac extended metadata. */
3948 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
3949 const void *metadata, size_t metadata_size)
3951 (void)a; /* UNUSED */
3952 (void)pathname; /* UNUSED */
3953 (void)metadata; /* UNUSED */
3954 (void)metadata_size; /* UNUSED */
3955 return (ARCHIVE_OK);
3959 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
3961 (void)a; /* UNUSED */
3962 (void)pathname; /* UNUSED */
3963 return (ARCHIVE_OK);
3968 * On Mac OS, we use copyfile() to unpack the metadata and
3969 * apply it to the target file.
3972 #if defined(HAVE_SYS_XATTR_H)
3974 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
3977 char *xattr_names = NULL, *xattr_val = NULL;
3978 int ret = ARCHIVE_OK, xattr_i;
3980 xattr_size = flistxattr(tmpfd, NULL, 0, 0);
3981 if (xattr_size == -1) {
3982 archive_set_error(&a->archive, errno,
3983 "Failed to read metadata(xattr)");
3987 xattr_names = malloc(xattr_size);
3988 if (xattr_names == NULL) {
3989 archive_set_error(&a->archive, ENOMEM,
3990 "Can't allocate memory for metadata(xattr)");
3991 ret = ARCHIVE_FATAL;
3994 xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
3995 if (xattr_size == -1) {
3996 archive_set_error(&a->archive, errno,
3997 "Failed to read metadata(xattr)");
4001 for (xattr_i = 0; xattr_i < xattr_size;
4002 xattr_i += strlen(xattr_names + xattr_i) + 1) {
4003 char *xattr_val_saved;
4007 s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
4009 archive_set_error(&a->archive, errno,
4010 "Failed to get metadata(xattr)");
4014 xattr_val_saved = xattr_val;
4015 xattr_val = realloc(xattr_val, s);
4016 if (xattr_val == NULL) {
4017 archive_set_error(&a->archive, ENOMEM,
4018 "Failed to get metadata(xattr)");
4020 free(xattr_val_saved);
4023 s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4025 archive_set_error(&a->archive, errno,
4026 "Failed to get metadata(xattr)");
4030 f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4032 archive_set_error(&a->archive, errno,
4033 "Failed to get metadata(xattr)");
4046 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
4048 #ifndef HAVE_SYS_ACL_H
4051 acl_t acl, dfacl = NULL;
4052 int acl_r, ret = ARCHIVE_OK;
4054 acl = acl_get_fd(tmpfd);
4056 if (errno == ENOENT)
4057 /* There are not any ACLs. */
4059 archive_set_error(&a->archive, errno,
4060 "Failed to get metadata(acl)");
4064 dfacl = acl_dup(acl);
4065 acl_r = acl_set_fd(dffd, dfacl);
4067 archive_set_error(&a->archive, errno,
4068 "Failed to get metadata(acl)");
4082 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4084 struct archive_string tmpdatafork;
4087 archive_string_init(&tmpdatafork);
4088 archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
4089 tmpfd = mkstemp(tmpdatafork.s);
4091 archive_set_error(&a->archive, errno,
4092 "Failed to mkstemp");
4093 archive_string_free(&tmpdatafork);
4096 if (copyfile(pathname, tmpdatafork.s, 0,
4097 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4098 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4099 archive_set_error(&a->archive, errno,
4100 "Failed to restore metadata");
4104 unlink(tmpdatafork.s);
4105 archive_string_free(&tmpdatafork);
4110 copy_metadata(struct archive_write_disk *a, const char *metadata,
4111 const char *datafork, int datafork_compressed)
4113 int ret = ARCHIVE_OK;
4115 if (datafork_compressed) {
4118 tmpfd = create_tempdatafork(a, metadata);
4120 return (ARCHIVE_WARN);
4123 * Do not open the data fork compressed by HFS+ compression
4124 * with at least a writing mode(O_RDWR or O_WRONLY). it
4125 * makes the data fork uncompressed.
4127 dffd = open(datafork, 0);
4129 archive_set_error(&a->archive, errno,
4130 "Failed to open the data fork for metadata");
4132 return (ARCHIVE_WARN);
4135 #if defined(HAVE_SYS_XATTR_H)
4136 ret = copy_xattrs(a, tmpfd, dffd);
4137 if (ret == ARCHIVE_OK)
4139 ret = copy_acls(a, tmpfd, dffd);
4143 if (copyfile(metadata, datafork, 0,
4144 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4145 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4146 archive_set_error(&a->archive, errno,
4147 "Failed to restore metadata");
4155 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4156 const void *metadata, size_t metadata_size)
4158 struct archive_string tmp;
4161 int ret = ARCHIVE_OK;
4163 /* This would be simpler if copyfile() could just accept the
4164 * metadata as a block of memory; then we could sidestep this
4165 * silly dance of writing the data to disk just so that
4166 * copyfile() can read it back in again. */
4167 archive_string_init(&tmp);
4168 archive_strcpy(&tmp, pathname);
4169 archive_strcat(&tmp, ".XXXXXX");
4170 fd = mkstemp(tmp.s);
4173 archive_set_error(&a->archive, errno,
4174 "Failed to restore metadata");
4175 archive_string_free(&tmp);
4176 return (ARCHIVE_WARN);
4178 written = write(fd, metadata, metadata_size);
4180 if ((size_t)written != metadata_size) {
4181 archive_set_error(&a->archive, errno,
4182 "Failed to restore metadata");
4187 #if defined(UF_COMPRESSED)
4188 if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
4189 (ret = lazy_stat(a)) == ARCHIVE_OK)
4190 compressed = a->st.st_flags & UF_COMPRESSED;
4194 ret = copy_metadata(a, tmp.s, pathname, compressed);
4197 archive_string_free(&tmp);
4202 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4207 struct archive_string datafork;
4208 int fd = -1, ret = ARCHIVE_OK;
4210 archive_string_init(&datafork);
4211 /* Check if the current file name is a type of the resource
4213 p = strrchr(pathname, '/');
4218 if (p[0] != '.' || p[1] != '_')
4219 goto skip_appledouble;
4222 * Check if the data fork file exists.
4224 * TODO: Check if this write disk object has handled it.
4226 archive_strncpy(&datafork, pathname, p - pathname);
4227 archive_strcat(&datafork, p + 2);
4228 if (lstat(datafork.s, &st) == -1 ||
4229 (st.st_mode & AE_IFMT) != AE_IFREG)
4230 goto skip_appledouble;
4233 * Check if the file is in the AppleDouble form.
4235 fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4236 __archive_ensure_cloexec_flag(fd);
4238 archive_set_error(&a->archive, errno,
4239 "Failed to open a restoring file");
4241 goto skip_appledouble;
4243 if (read(fd, buff, 8) == -1) {
4244 archive_set_error(&a->archive, errno,
4245 "Failed to read a restoring file");
4248 goto skip_appledouble;
4251 /* Check AppleDouble Magic Code. */
4252 if (archive_be32dec(buff) != 0x00051607)
4253 goto skip_appledouble;
4254 /* Check AppleDouble Version. */
4255 if (archive_be32dec(buff+4) != 0x00020000)
4256 goto skip_appledouble;
4258 ret = copy_metadata(a, pathname, datafork.s,
4259 #if defined(UF_COMPRESSED)
4260 st.st_flags & UF_COMPRESSED);
4264 if (ret == ARCHIVE_OK) {
4269 archive_string_free(&datafork);
4274 #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4276 * Restore extended attributes - Linux, Darwin and AIX implementations:
4277 * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4280 set_xattrs(struct archive_write_disk *a)
4282 struct archive_entry *entry = a->entry;
4283 struct archive_string errlist;
4284 int ret = ARCHIVE_OK;
4285 int i = archive_entry_xattr_reset(entry);
4288 archive_string_init(&errlist);
4296 archive_entry_xattr_next(entry, &name, &value, &size);
4300 #if ARCHIVE_XATTR_LINUX
4301 /* Linux: quietly skip POSIX.1e ACL extended attributes */
4302 if (strncmp(name, "system.", 7) == 0 &&
4303 (strcmp(name + 7, "posix_acl_access") == 0 ||
4304 strcmp(name + 7, "posix_acl_default") == 0))
4306 if (strncmp(name, "trusted.SGI_", 12) == 0 &&
4307 (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
4308 strcmp(name + 12, "ACL_FILE") == 0))
4311 /* Linux: xfsroot namespace is obsolete and unsupported */
4312 if (strncmp(name, "xfsroot.", 8) == 0) {
4314 archive_strcat(&errlist, name);
4315 archive_strappend_char(&errlist, ' ');
4321 #if ARCHIVE_XATTR_LINUX
4322 e = fsetxattr(a->fd, name, value, size, 0);
4323 #elif ARCHIVE_XATTR_DARWIN
4324 e = fsetxattr(a->fd, name, value, size, 0, 0);
4325 #elif ARCHIVE_XATTR_AIX
4326 e = fsetea(a->fd, name, value, size, 0);
4329 #if ARCHIVE_XATTR_LINUX
4330 e = lsetxattr(archive_entry_pathname(entry),
4331 name, value, size, 0);
4332 #elif ARCHIVE_XATTR_DARWIN
4333 e = setxattr(archive_entry_pathname(entry),
4334 name, value, size, 0, XATTR_NOFOLLOW);
4335 #elif ARCHIVE_XATTR_AIX
4336 e = lsetea(archive_entry_pathname(entry),
4337 name, value, size, 0);
4342 archive_strcat(&errlist, name);
4343 archive_strappend_char(&errlist, ' ');
4344 if (errno != ENOTSUP && errno != ENOSYS)
4349 if (ret == ARCHIVE_WARN) {
4350 if (fail && errlist.length > 0) {
4352 errlist.s[errlist.length] = '\0';
4353 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4354 "Cannot restore extended attributes: %s",
4357 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4358 "Cannot restore extended "
4359 "attributes on this file system.");
4362 archive_string_free(&errlist);
4365 #elif ARCHIVE_XATTR_FREEBSD
4367 * Restore extended attributes - FreeBSD implementation
4370 set_xattrs(struct archive_write_disk *a)
4372 struct archive_entry *entry = a->entry;
4373 struct archive_string errlist;
4374 int ret = ARCHIVE_OK;
4375 int i = archive_entry_xattr_reset(entry);
4378 archive_string_init(&errlist);
4384 archive_entry_xattr_next(entry, &name, &value, &size);
4389 if (strncmp(name, "user.", 5) == 0) {
4390 /* "user." attributes go to user namespace */
4392 namespace = EXTATTR_NAMESPACE_USER;
4394 /* Other namespaces are unsupported */
4395 archive_strcat(&errlist, name);
4396 archive_strappend_char(&errlist, ' ');
4403 e = extattr_set_fd(a->fd, namespace, name,
4406 e = extattr_set_link(
4407 archive_entry_pathname(entry), namespace,
4410 if (e != (ssize_t)size) {
4411 archive_strcat(&errlist, name);
4412 archive_strappend_char(&errlist, ' ');
4414 if (errno != ENOTSUP && errno != ENOSYS)
4420 if (ret == ARCHIVE_WARN) {
4421 if (fail && errlist.length > 0) {
4423 errlist.s[errlist.length] = '\0';
4425 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4426 "Cannot restore extended attributes: %s",
4429 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4430 "Cannot restore extended "
4431 "attributes on this file system.");
4434 archive_string_free(&errlist);
4439 * Restore extended attributes - stub implementation for unsupported systems
4442 set_xattrs(struct archive_write_disk *a)
4444 static int warning_done = 0;
4446 /* If there aren't any extended attributes, then it's okay not
4447 * to extract them, otherwise, issue a single warning. */
4448 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4450 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4451 "Cannot restore extended attributes on this system");
4452 return (ARCHIVE_WARN);
4454 /* Warning was already emitted; suppress further warnings. */
4455 return (ARCHIVE_OK);
4460 * Test if file on disk is older than entry.
4463 older(struct stat *st, struct archive_entry *entry)
4465 /* First, test the seconds and return if we have a definite answer. */
4466 /* Definitely older. */
4467 if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry)))
4469 /* Definitely younger. */
4470 if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4472 /* If this platform supports fractional seconds, try those. */
4473 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4474 /* Definitely older. */
4475 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4477 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4478 /* Definitely older. */
4479 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4481 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4483 if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4485 #elif HAVE_STRUCT_STAT_ST_UMTIME
4487 if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4489 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4491 if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4494 /* This system doesn't have high-res timestamps. */
4496 /* Same age or newer, so not older. */
4500 #ifndef ARCHIVE_ACL_SUPPORT
4502 archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4503 struct archive_acl *abstract_acl, __LA_MODE_T mode)
4505 (void)a; /* UNUSED */
4506 (void)fd; /* UNUSED */
4507 (void)name; /* UNUSED */
4508 (void)abstract_acl; /* UNUSED */
4509 (void)mode; /* UNUSED */
4510 return (ARCHIVE_OK);
4514 #endif /* !_WIN32 || __CYGWIN__ */