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
134 #include <cm3p/zlib.h>
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;
176 __LA_MODE_T filetype;
181 unsigned long atime_nanos;
182 unsigned long birthtime_nanos;
183 unsigned long mtime_nanos;
184 unsigned long ctime_nanos;
185 unsigned long fflags_set;
186 size_t mac_metadata_size;
188 int fixup; /* bitmask of what needs fixing */
193 * We use a bitmask to track which operations remain to be done for
194 * this file. In particular, this helps us avoid unnecessary
195 * operations when it's possible to take care of one step as a
196 * side-effect of another. For example, mkdir() can specify the mode
197 * for the newly-created object but symlink() cannot. This means we
198 * can skip chmod() if mkdir() succeeded, but we must explicitly
199 * chmod() if we're trying to create a directory that already exists
200 * (mkdir() failed) or if we're restoring a symlink. Similarly, we
201 * need to verify UID/GID before trying to restore SUID/SGID bits;
202 * that verification can occur explicitly through a stat() call or
203 * implicitly because of a successful chown() call.
205 #define TODO_MODE_FORCE 0x40000000
206 #define TODO_MODE_BASE 0x20000000
207 #define TODO_SUID 0x10000000
208 #define TODO_SUID_CHECK 0x08000000
209 #define TODO_SGID 0x04000000
210 #define TODO_SGID_CHECK 0x02000000
211 #define TODO_APPLEDOUBLE 0x01000000
212 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
213 #define TODO_TIMES ARCHIVE_EXTRACT_TIME
214 #define TODO_OWNER ARCHIVE_EXTRACT_OWNER
215 #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
216 #define TODO_ACLS ARCHIVE_EXTRACT_ACL
217 #define TODO_XATTR ARCHIVE_EXTRACT_XATTR
218 #define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA
219 #define TODO_HFS_COMPRESSION ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED
221 struct archive_write_disk {
222 struct archive archive;
225 struct fixup_entry *fixup_list;
226 struct fixup_entry *current_fixup;
229 int64_t skip_file_dev;
230 int64_t skip_file_ino;
233 int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid);
234 void (*cleanup_gid)(void *private);
235 void *lookup_gid_data;
236 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid);
237 void (*cleanup_uid)(void *private);
238 void *lookup_uid_data;
241 * Full path of last file to satisfy symlink checks.
243 struct archive_string path_safe;
246 * Cached stat data from disk for the current entry.
247 * If this is valid, pst points to st. Otherwise,
253 /* Information about the object being restored right now. */
254 struct archive_entry *entry; /* Entry being extracted. */
255 char *name; /* Name of entry, possibly edited. */
256 struct archive_string _name_data; /* backing store for 'name' */
257 char *tmpname; /* Temporary name * */
258 struct archive_string _tmpname_data; /* backing store for 'tmpname' */
259 /* Tasks remaining for this object. */
261 /* Tasks deferred until end-of-archive. */
263 /* Options requested by the client. */
265 /* Handle for the file we're restoring. */
267 /* Current offset for writing data to the file. */
269 /* Last offset actually written to disk. */
271 /* Total bytes actually written to files. */
272 int64_t total_bytes_written;
273 /* Maximum size of file, -1 if unknown. */
275 /* Dir we were in before this restore; only for deep paths. */
277 /* Mode we should use for this entry; affected by _PERM and umask. */
279 /* UID/GID to use in restoring this entry. */
285 /* Xattr "com.apple.decmpfs". */
286 uint32_t decmpfs_attr_size;
287 unsigned char *decmpfs_header_p;
288 /* ResourceFork set options used for fsetxattr. */
289 int rsrc_xattr_options;
290 /* Xattr "com.apple.ResourceFork". */
291 unsigned char *resource_fork;
292 size_t resource_fork_allocated_size;
293 unsigned int decmpfs_block_count;
294 uint32_t *decmpfs_block_info;
295 /* Buffer for compressed data. */
296 unsigned char *compressed_buffer;
297 size_t compressed_buffer_size;
298 size_t compressed_buffer_remaining;
299 /* The offset of the ResourceFork where compressed data will
301 uint32_t compressed_rsrc_position;
302 uint32_t compressed_rsrc_position_v;
303 /* Buffer for uncompressed data. */
304 char *uncompressed_buffer;
305 size_t block_remaining_bytes;
306 size_t file_remaining_bytes;
310 int decmpfs_compression_level;
315 * Default mode for dirs created automatically (will be modified by umask).
316 * Note that POSIX specifies 0777 for implicitly-created dirs, "modified
317 * by the process' file creation mask."
319 #define DEFAULT_DIR_MODE 0777
321 * Dir modes are restored in two steps: During the extraction, the permissions
322 * in the archive are modified to match the following limits. During
323 * the post-extract fixup pass, the permissions from the archive are
326 #define MINIMUM_DIR_MODE 0700
327 #define MAXIMUM_DIR_MODE 0775
330 * Maximum uncompressed size of a decmpfs block.
332 #define MAX_DECMPFS_BLOCK_SIZE (64 * 1024)
334 * HFS+ compression type.
336 #define CMP_XATTR 3/* Compressed data in xattr. */
337 #define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */
339 * HFS+ compression resource fork.
341 #define RSRC_H_SIZE 260 /* Base size of Resource fork header. */
342 #define RSRC_F_SIZE 50 /* Size of Resource fork footer. */
343 /* Size to write compressed data to resource fork. */
344 #define COMPRESSED_W_SIZE (64 * 1024)
345 /* decmpfs definitions. */
346 #define MAX_DECMPFS_XATTR_SIZE 3802
347 #ifndef DECMPFS_XATTR_NAME
348 #define DECMPFS_XATTR_NAME "com.apple.decmpfs"
350 #define DECMPFS_MAGIC 0x636d7066
351 #define DECMPFS_COMPRESSION_MAGIC 0
352 #define DECMPFS_COMPRESSION_TYPE 4
353 #define DECMPFS_UNCOMPRESSED_SIZE 8
354 #define DECMPFS_HEADER_SIZE 16
356 #define HFS_BLOCKS(s) ((s) >> 12)
359 static int la_opendirat(int, const char *);
360 static int la_mktemp(struct archive_write_disk *);
361 static int la_verify_filetype(mode_t, __LA_MODE_T);
362 static void fsobj_error(int *, struct archive_string *, int, const char *,
364 static int check_symlinks_fsobj(char *, int *, struct archive_string *,
366 static int check_symlinks(struct archive_write_disk *);
367 static int create_filesystem_object(struct archive_write_disk *);
368 static struct fixup_entry *current_fixup(struct archive_write_disk *,
369 const char *pathname);
370 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
371 static void edit_deep_directories(struct archive_write_disk *ad);
373 static int cleanup_pathname_fsobj(char *, int *, struct archive_string *,
375 static int cleanup_pathname(struct archive_write_disk *);
376 static int create_dir(struct archive_write_disk *, char *);
377 static int create_parent_dir(struct archive_write_disk *, char *);
378 static ssize_t hfs_write_data_block(struct archive_write_disk *,
379 const char *, size_t);
380 static int fixup_appledouble(struct archive_write_disk *, const char *);
381 static int older(struct stat *, struct archive_entry *);
382 static int restore_entry(struct archive_write_disk *);
383 static int set_mac_metadata(struct archive_write_disk *, const char *,
384 const void *, size_t);
385 static int set_xattrs(struct archive_write_disk *);
386 static int clear_nochange_fflags(struct archive_write_disk *);
387 static int set_fflags(struct archive_write_disk *);
388 static int set_fflags_platform(struct archive_write_disk *, int fd,
389 const char *name, mode_t mode,
390 unsigned long fflags_set, unsigned long fflags_clear);
391 static int set_ownership(struct archive_write_disk *);
392 static int set_mode(struct archive_write_disk *, int mode);
393 static int set_time(int, int, const char *, time_t, long, time_t, long);
394 static int set_times(struct archive_write_disk *, int, int, const char *,
395 time_t, long, time_t, long, time_t, long, time_t, long);
396 static int set_times_from_entry(struct archive_write_disk *);
397 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
398 static ssize_t write_data_block(struct archive_write_disk *,
399 const char *, size_t);
401 static struct archive_vtable *archive_write_disk_vtable(void);
403 static int _archive_write_disk_close(struct archive *);
404 static int _archive_write_disk_free(struct archive *);
405 static int _archive_write_disk_header(struct archive *,
406 struct archive_entry *);
407 static int64_t _archive_write_disk_filter_bytes(struct archive *, int);
408 static int _archive_write_disk_finish_entry(struct archive *);
409 static ssize_t _archive_write_disk_data(struct archive *, const void *,
411 static ssize_t _archive_write_disk_data_block(struct archive *, const void *,
415 la_mktemp(struct archive_write_disk *a)
420 archive_string_empty(&a->_tmpname_data);
421 archive_string_sprintf(&a->_tmpname_data, "%s.XXXXXX", a->name);
422 a->tmpname = a->_tmpname_data.s;
424 fd = __archive_mkstemp(a->tmpname);
428 mode = a->mode & 0777 & ~a->user_umask;
429 if (fchmod(fd, mode) == -1) {
439 la_opendirat(int fd, const char *path) {
440 const int flags = O_CLOEXEC
441 #if defined(O_BINARY)
444 #if defined(O_DIRECTORY)
449 #elif defined(O_SEARCH)
451 #elif defined(__FreeBSD__) && defined(O_EXEC)
458 #if !defined(HAVE_OPENAT)
459 if (fd != AT_FDCWD) {
463 return (open(path, flags));
465 return (openat(fd, path, flags));
470 la_verify_filetype(mode_t mode, __LA_MODE_T filetype) {
475 ret = (S_ISREG(mode));
478 ret = (S_ISDIR(mode));
481 ret = (S_ISLNK(mode));
484 ret = (S_ISSOCK(mode));
487 ret = (S_ISCHR(mode));
490 ret = (S_ISBLK(mode));
493 ret = (S_ISFIFO(mode));
503 lazy_stat(struct archive_write_disk *a)
505 if (a->pst != NULL) {
506 /* Already have stat() data available. */
510 if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
516 * XXX At this point, symlinks should not be hit, otherwise
517 * XXX a race occurred. Do we want to check explicitly for that?
519 if (lstat(a->name, &a->st) == 0) {
523 archive_set_error(&a->archive, errno, "Couldn't stat file");
524 return (ARCHIVE_WARN);
527 static struct archive_vtable *
528 archive_write_disk_vtable(void)
530 static struct archive_vtable av;
531 static int inited = 0;
534 av.archive_close = _archive_write_disk_close;
535 av.archive_filter_bytes = _archive_write_disk_filter_bytes;
536 av.archive_free = _archive_write_disk_free;
537 av.archive_write_header = _archive_write_disk_header;
538 av.archive_write_finish_entry
539 = _archive_write_disk_finish_entry;
540 av.archive_write_data = _archive_write_disk_data;
541 av.archive_write_data_block = _archive_write_disk_data_block;
548 _archive_write_disk_filter_bytes(struct archive *_a, int n)
550 struct archive_write_disk *a = (struct archive_write_disk *)_a;
551 (void)n; /* UNUSED */
552 if (n == -1 || n == 0)
553 return (a->total_bytes_written);
559 archive_write_disk_set_options(struct archive *_a, int flags)
561 struct archive_write_disk *a = (struct archive_write_disk *)_a;
569 * Extract this entry to disk.
571 * TODO: Validate hardlinks. According to the standards, we're
572 * supposed to check each extracted hardlink and squawk if it refers
573 * to a file that we didn't restore. I'm not entirely convinced this
574 * is a good idea, but more importantly: Is there any way to validate
575 * hardlinks without keeping a complete list of filenames from the
576 * entire archive?? Ugh.
580 _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
582 struct archive_write_disk *a = (struct archive_write_disk *)_a;
583 struct fixup_entry *fe;
584 const char *linkname;
587 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
588 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
589 "archive_write_disk_header");
590 archive_clear_error(&a->archive);
591 if (a->archive.state & ARCHIVE_STATE_DATA) {
592 r = _archive_write_disk_finish_entry(&a->archive);
593 if (r == ARCHIVE_FATAL)
597 /* Set up for this particular entry. */
599 a->current_fixup = NULL;
602 archive_entry_free(a->entry);
605 a->entry = archive_entry_clone(entry);
610 a->uid = a->user_uid;
611 a->mode = archive_entry_mode(a->entry);
612 if (archive_entry_size_is_set(a->entry))
613 a->filesize = archive_entry_size(a->entry);
616 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
617 a->name = a->_name_data.s;
618 archive_clear_error(&a->archive);
621 * Clean up the requested path. This is necessary for correct
622 * dir restores; the dir restore logic otherwise gets messed
623 * up by nonsense like "dir/.".
625 ret = cleanup_pathname(a);
626 if (ret != ARCHIVE_OK)
630 * Check if we have a hardlink that points to itself.
632 linkname = archive_entry_hardlink(a->entry);
633 if (linkname != NULL && strcmp(a->name, linkname) == 0) {
634 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
635 "Skipping hardlink pointing to itself: %s",
637 return (ARCHIVE_WARN);
641 * Query the umask so we get predictable mode settings.
642 * This gets done on every call to _write_header in case the
643 * user edits their umask during the extraction for some
646 umask(a->user_umask = umask(0));
648 /* Figure out what we need to do for this entry. */
649 a->todo = TODO_MODE_BASE;
650 if (a->flags & ARCHIVE_EXTRACT_PERM) {
651 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
653 * SGID requires an extra "check" step because we
654 * cannot easily predict the GID that the system will
655 * assign. (Different systems assign GIDs to files
656 * based on a variety of criteria, including process
657 * credentials and the gid of the enclosing
658 * directory.) We can only restore the SGID bit if
659 * the file has the right GID, and we only know the
660 * GID if we either set it (see set_ownership) or if
661 * we've actually called stat() on the file after it
662 * was restored. Since there are several places at
663 * which we might verify the GID, we need a TODO bit
666 if (a->mode & S_ISGID)
667 a->todo |= TODO_SGID | TODO_SGID_CHECK;
669 * Verifying the SUID is simpler, but can still be
670 * done in multiple ways, hence the separate "check" bit.
672 if (a->mode & S_ISUID)
673 a->todo |= TODO_SUID | TODO_SUID_CHECK;
676 * User didn't request full permissions, so don't
677 * restore SUID, SGID bits and obey umask.
682 a->mode &= ~a->user_umask;
684 if (a->flags & ARCHIVE_EXTRACT_OWNER)
685 a->todo |= TODO_OWNER;
686 if (a->flags & ARCHIVE_EXTRACT_TIME)
687 a->todo |= TODO_TIMES;
688 if (a->flags & ARCHIVE_EXTRACT_ACL) {
689 #if ARCHIVE_ACL_DARWIN
691 * On MacOS, platform ACLs get stored in mac_metadata, too.
692 * If we intend to extract mac_metadata and it is present
693 * we skip extracting libarchive NFSv4 ACLs.
695 size_t metadata_size;
697 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
698 archive_entry_mac_metadata(a->entry,
699 &metadata_size) == NULL || metadata_size == 0)
701 #if ARCHIVE_ACL_LIBRICHACL
703 * RichACLs are stored in an extended attribute.
704 * If we intend to extract extended attributes and have this
705 * attribute we skip extracting libarchive NFSv4 ACLs.
707 short extract_acls = 1;
708 if (a->flags & ARCHIVE_EXTRACT_XATTR && (
709 archive_entry_acl_types(a->entry) &
710 ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
711 const char *attr_name;
712 const void *attr_value;
714 int i = archive_entry_xattr_reset(a->entry);
716 archive_entry_xattr_next(a->entry, &attr_name,
717 &attr_value, &attr_size);
718 if (attr_name != NULL && attr_value != NULL &&
719 attr_size > 0 && strcmp(attr_name,
720 "trusted.richacl") == 0) {
728 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
731 if (archive_entry_filetype(a->entry) == AE_IFDIR)
732 a->deferred |= TODO_ACLS;
734 a->todo |= TODO_ACLS;
735 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
739 if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
740 if (archive_entry_filetype(a->entry) == AE_IFDIR)
741 a->deferred |= TODO_MAC_METADATA;
743 a->todo |= TODO_MAC_METADATA;
745 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
746 if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
747 unsigned long set, clear;
748 archive_entry_fflags(a->entry, &set, &clear);
749 if ((set & ~clear) & UF_COMPRESSED) {
750 a->todo |= TODO_HFS_COMPRESSION;
751 a->decmpfs_block_count = (unsigned)-1;
754 if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
755 (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
756 a->todo |= TODO_HFS_COMPRESSION;
757 a->decmpfs_block_count = (unsigned)-1;
762 /* Check if the current file name is a type of the
763 * resource fork file. */
764 p = strrchr(a->name, '/');
769 if (p[0] == '.' && p[1] == '_') {
770 /* Do not compress "._XXX" files. */
771 a->todo &= ~TODO_HFS_COMPRESSION;
773 a->todo |= TODO_APPLEDOUBLE;
778 if (a->flags & ARCHIVE_EXTRACT_XATTR) {
779 #if ARCHIVE_XATTR_DARWIN
781 * On MacOS, extended attributes get stored in mac_metadata,
782 * too. If we intend to extract mac_metadata and it is present
783 * we skip extracting extended attributes.
785 size_t metadata_size;
787 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
788 archive_entry_mac_metadata(a->entry,
789 &metadata_size) == NULL || metadata_size == 0)
791 a->todo |= TODO_XATTR;
793 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
794 a->todo |= TODO_FFLAGS;
795 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
796 ret = check_symlinks(a);
797 if (ret != ARCHIVE_OK)
800 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
801 /* If path exceeds PATH_MAX, shorten the path. */
802 edit_deep_directories(a);
805 ret = restore_entry(a);
807 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
809 * Check if the filesystem the file is restoring on supports
810 * HFS+ Compression. If not, cancel HFS+ Compression.
812 if (a->todo | TODO_HFS_COMPRESSION) {
814 * NOTE: UF_COMPRESSED is ignored even if the filesystem
815 * supports HFS+ Compression because the file should
816 * have at least an extended attribute "com.apple.decmpfs"
817 * before the flag is set to indicate that the file have
818 * been compressed. If the filesystem does not support
819 * HFS+ Compression the system call will fail.
821 if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
822 a->todo &= ~TODO_HFS_COMPRESSION;
827 * TODO: There are rumours that some extended attributes must
828 * be restored before file data is written. If this is true,
829 * then we either need to write all extended attributes both
830 * before and after restoring the data, or find some rule for
831 * determining which must go first and which last. Due to the
832 * many ways people are using xattrs, this may prove to be an
833 * intractable problem.
837 /* If we changed directory above, restore it here. */
838 if (a->restore_pwd >= 0) {
839 r = fchdir(a->restore_pwd);
841 archive_set_error(&a->archive, errno,
845 close(a->restore_pwd);
851 * Fixup uses the unedited pathname from archive_entry_pathname(),
852 * because it is relative to the base dir and the edited path
853 * might be relative to some intermediate dir as a result of the
854 * deep restore logic.
856 if (a->deferred & TODO_MODE) {
857 fe = current_fixup(a, archive_entry_pathname(entry));
859 return (ARCHIVE_FATAL);
860 fe->filetype = archive_entry_filetype(entry);
861 fe->fixup |= TODO_MODE_BASE;
865 if ((a->deferred & TODO_TIMES)
866 && (archive_entry_mtime_is_set(entry)
867 || archive_entry_atime_is_set(entry))) {
868 fe = current_fixup(a, archive_entry_pathname(entry));
870 return (ARCHIVE_FATAL);
871 fe->filetype = archive_entry_filetype(entry);
873 fe->fixup |= TODO_TIMES;
874 if (archive_entry_atime_is_set(entry)) {
875 fe->atime = archive_entry_atime(entry);
876 fe->atime_nanos = archive_entry_atime_nsec(entry);
878 /* If atime is unset, use start time. */
879 fe->atime = a->start_time;
882 if (archive_entry_mtime_is_set(entry)) {
883 fe->mtime = archive_entry_mtime(entry);
884 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
886 /* If mtime is unset, use start time. */
887 fe->mtime = a->start_time;
890 if (archive_entry_birthtime_is_set(entry)) {
891 fe->birthtime = archive_entry_birthtime(entry);
892 fe->birthtime_nanos = archive_entry_birthtime_nsec(
895 /* If birthtime is unset, use mtime. */
896 fe->birthtime = fe->mtime;
897 fe->birthtime_nanos = fe->mtime_nanos;
901 if (a->deferred & TODO_ACLS) {
902 fe = current_fixup(a, archive_entry_pathname(entry));
904 return (ARCHIVE_FATAL);
905 fe->filetype = archive_entry_filetype(entry);
906 fe->fixup |= TODO_ACLS;
907 archive_acl_copy(&fe->acl, archive_entry_acl(entry));
910 if (a->deferred & TODO_MAC_METADATA) {
911 const void *metadata;
912 size_t metadata_size;
913 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
914 if (metadata != NULL && metadata_size > 0) {
915 fe = current_fixup(a, archive_entry_pathname(entry));
917 return (ARCHIVE_FATAL);
918 fe->filetype = archive_entry_filetype(entry);
919 fe->mac_metadata = malloc(metadata_size);
920 if (fe->mac_metadata != NULL) {
921 memcpy(fe->mac_metadata, metadata,
923 fe->mac_metadata_size = metadata_size;
924 fe->fixup |= TODO_MAC_METADATA;
929 if (a->deferred & TODO_FFLAGS) {
930 fe = current_fixup(a, archive_entry_pathname(entry));
932 return (ARCHIVE_FATAL);
933 fe->filetype = archive_entry_filetype(entry);
934 fe->fixup |= TODO_FFLAGS;
935 /* TODO: Complete this.. defer fflags from below. */
938 /* We've created the object and are ready to pour data into it. */
939 if (ret >= ARCHIVE_WARN)
940 a->archive.state = ARCHIVE_STATE_DATA;
942 * If it's not open, tell our client not to try writing.
943 * In particular, dirs, links, etc, don't get written to.
946 archive_entry_set_size(entry, 0);
954 archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
956 struct archive_write_disk *a = (struct archive_write_disk *)_a;
957 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
958 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
959 a->skip_file_set = 1;
960 a->skip_file_dev = d;
961 a->skip_file_ino = i;
966 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
968 uint64_t start_size = size;
969 ssize_t bytes_written = 0;
970 ssize_t block_size = 0, bytes_to_write;
975 if (a->filesize == 0 || a->fd < 0) {
976 archive_set_error(&a->archive, 0,
977 "Attempt to write to an empty file");
978 return (ARCHIVE_WARN);
981 if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
982 #if HAVE_STRUCT_STAT_ST_BLKSIZE
984 if ((r = lazy_stat(a)) != ARCHIVE_OK)
986 block_size = a->pst->st_blksize;
988 /* XXX TODO XXX Is there a more appropriate choice here ? */
989 /* This needn't match the filesystem allocation size. */
990 block_size = 16*1024;
994 /* If this write would run beyond the file size, truncate it. */
995 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
996 start_size = size = (size_t)(a->filesize - a->offset);
998 /* Write the data. */
1000 if (block_size == 0) {
1001 bytes_to_write = size;
1003 /* We're sparsifying the file. */
1004 const char *p, *end;
1007 /* Skip leading zero bytes. */
1008 for (p = buff, end = buff + size; p < end; ++p) {
1012 a->offset += p - buff;
1018 /* Calculate next block boundary after offset. */
1020 = (a->offset / block_size + 1) * block_size;
1022 /* If the adjusted write would cross block boundary,
1023 * truncate it to the block boundary. */
1024 bytes_to_write = size;
1025 if (a->offset + bytes_to_write > block_end)
1026 bytes_to_write = block_end - a->offset;
1028 /* Seek if necessary to the specified offset. */
1029 if (a->offset != a->fd_offset) {
1030 if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
1031 archive_set_error(&a->archive, errno,
1033 return (ARCHIVE_FATAL);
1035 a->fd_offset = a->offset;
1037 bytes_written = write(a->fd, buff, bytes_to_write);
1038 if (bytes_written < 0) {
1039 archive_set_error(&a->archive, errno, "Write failed");
1040 return (ARCHIVE_WARN);
1042 buff += bytes_written;
1043 size -= bytes_written;
1044 a->total_bytes_written += bytes_written;
1045 a->offset += bytes_written;
1046 a->fd_offset = a->offset;
1048 return (start_size - size);
1051 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
1052 && defined(HAVE_ZLIB_H)
1055 * Set UF_COMPRESSED file flag.
1056 * This have to be called after hfs_write_decmpfs() because if the
1057 * file does not have "com.apple.decmpfs" xattr the flag is ignored.
1060 hfs_set_compressed_fflag(struct archive_write_disk *a)
1064 if ((r = lazy_stat(a)) != ARCHIVE_OK)
1067 a->st.st_flags |= UF_COMPRESSED;
1068 if (fchflags(a->fd, a->st.st_flags) != 0) {
1069 archive_set_error(&a->archive, errno,
1070 "Failed to set UF_COMPRESSED file flag");
1071 return (ARCHIVE_WARN);
1073 return (ARCHIVE_OK);
1077 * HFS+ Compression decmpfs
1079 * +------------------------------+ +0
1080 * | Magic(LE 4 bytes) |
1081 * +------------------------------+
1082 * | Type(LE 4 bytes) |
1083 * +------------------------------+
1084 * | Uncompressed size(LE 8 bytes)|
1085 * +------------------------------+ +16
1087 * | Compressed data |
1088 * | (Placed only if Type == 3) |
1090 * +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE
1092 * Type is 3: decmpfs has compressed data.
1093 * Type is 4: Resource Fork has compressed data.
1096 * Write "com.apple.decmpfs"
1099 hfs_write_decmpfs(struct archive_write_disk *a)
1102 uint32_t compression_type;
1104 r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1105 a->decmpfs_attr_size, 0, 0);
1107 archive_set_error(&a->archive, errno,
1108 "Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
1109 compression_type = archive_le32dec(
1110 &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
1111 if (compression_type == CMP_RESOURCE_FORK)
1112 fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
1113 XATTR_SHOWCOMPRESSION);
1114 return (ARCHIVE_WARN);
1116 return (ARCHIVE_OK);
1120 * HFS+ Compression Resource Fork
1122 * +-----------------------------+
1123 * | Header(260 bytes) |
1124 * +-----------------------------+
1125 * | Block count(LE 4 bytes) |
1126 * +-----------------------------+ --+
1127 * +-- | Offset (LE 4 bytes) | |
1128 * | | [distance from Block count] | | Block 0
1129 * | +-----------------------------+ |
1130 * | | Compressed size(LE 4 bytes) | |
1131 * | +-----------------------------+ --+
1133 * | | .................. |
1135 * | +-----------------------------+ --+
1136 * | | Offset (LE 4 bytes) | |
1137 * | +-----------------------------+ | Block (Block count -1)
1138 * | | Compressed size(LE 4 bytes) | |
1139 * +-> +-----------------------------+ --+
1140 * | Compressed data(n bytes) | Block 0
1141 * +-----------------------------+
1143 * | .................. |
1145 * +-----------------------------+
1146 * | Compressed data(n bytes) | Block (Block count -1)
1147 * +-----------------------------+
1148 * | Footer(50 bytes) |
1149 * +-----------------------------+
1153 * Write the header of "com.apple.ResourceFork"
1156 hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1157 size_t bytes, uint32_t position)
1161 ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1162 position, a->rsrc_xattr_options);
1164 archive_set_error(&a->archive, errno,
1165 "Cannot restore xattr: %s at %u pos %u bytes",
1166 XATTR_RESOURCEFORK_NAME,
1169 return (ARCHIVE_WARN);
1171 a->rsrc_xattr_options &= ~XATTR_CREATE;
1172 return (ARCHIVE_OK);
1176 hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1180 ret = hfs_write_resource_fork(a, a->compressed_buffer,
1181 bytes_compressed, a->compressed_rsrc_position);
1182 if (ret == ARCHIVE_OK)
1183 a->compressed_rsrc_position += bytes_compressed;
1188 hfs_write_resource_fork_header(struct archive_write_disk *a)
1190 unsigned char *buff;
1191 uint32_t rsrc_bytes;
1192 uint32_t rsrc_header_bytes;
1195 * Write resource fork header + block info.
1197 buff = a->resource_fork;
1198 rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1200 RSRC_H_SIZE + /* Header base size. */
1201 4 + /* Block count. */
1202 (a->decmpfs_block_count * 8);/* Block info */
1203 archive_be32enc(buff, 0x100);
1204 archive_be32enc(buff + 4, rsrc_bytes);
1205 archive_be32enc(buff + 8, rsrc_bytes - 256);
1206 archive_be32enc(buff + 12, 0x32);
1207 memset(buff + 16, 0, 240);
1208 archive_be32enc(buff + 256, rsrc_bytes - 260);
1209 return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
1213 hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1215 static const char rsrc_footer[RSRC_F_SIZE] = {
1216 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1217 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1218 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1219 0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm',
1220 'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
1221 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1224 if (buff_size < sizeof(rsrc_footer))
1226 memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1227 return (sizeof(rsrc_footer));
1231 hfs_reset_compressor(struct archive_write_disk *a)
1235 if (a->stream_valid)
1236 ret = deflateReset(&a->stream);
1238 ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1241 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1242 "Failed to initialize compressor");
1243 return (ARCHIVE_FATAL);
1245 a->stream_valid = 1;
1247 return (ARCHIVE_OK);
1251 hfs_decompress(struct archive_write_disk *a)
1253 uint32_t *block_info;
1254 unsigned int block_count;
1255 uint32_t data_pos, data_size;
1257 ssize_t bytes_written, bytes_to_write;
1260 block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1261 block_count = archive_le32dec(block_info++);
1262 while (block_count--) {
1263 data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
1264 data_size = archive_le32dec(block_info++);
1265 r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
1266 a->compressed_buffer, data_size, data_pos, 0);
1267 if (r != data_size) {
1268 archive_set_error(&a->archive,
1269 (r < 0)?errno:ARCHIVE_ERRNO_MISC,
1270 "Failed to read resource fork");
1271 return (ARCHIVE_WARN);
1273 if (a->compressed_buffer[0] == 0xff) {
1274 bytes_to_write = data_size -1;
1275 b = a->compressed_buffer + 1;
1277 uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1280 zr = uncompress((Bytef *)a->uncompressed_buffer,
1281 &dest_len, a->compressed_buffer, data_size);
1283 archive_set_error(&a->archive,
1285 "Failed to decompress resource fork");
1286 return (ARCHIVE_WARN);
1288 bytes_to_write = dest_len;
1289 b = (unsigned char *)a->uncompressed_buffer;
1292 bytes_written = write(a->fd, b, bytes_to_write);
1293 if (bytes_written < 0) {
1294 archive_set_error(&a->archive, errno,
1296 return (ARCHIVE_WARN);
1298 bytes_to_write -= bytes_written;
1300 } while (bytes_to_write > 0);
1302 r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1304 archive_set_error(&a->archive, errno,
1305 "Failed to remove resource fork");
1306 return (ARCHIVE_WARN);
1308 return (ARCHIVE_OK);
1312 hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1315 unsigned char *buffer_compressed;
1316 size_t bytes_compressed;
1320 ret = hfs_reset_compressor(a);
1321 if (ret != ARCHIVE_OK)
1324 if (a->compressed_buffer == NULL) {
1327 block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
1328 + compressBound(MAX_DECMPFS_BLOCK_SIZE);
1329 a->compressed_buffer = malloc(block_size);
1330 if (a->compressed_buffer == NULL) {
1331 archive_set_error(&a->archive, ENOMEM,
1332 "Can't allocate memory for Resource Fork");
1333 return (ARCHIVE_FATAL);
1335 a->compressed_buffer_size = block_size;
1336 a->compressed_buffer_remaining = block_size;
1339 buffer_compressed = a->compressed_buffer +
1340 a->compressed_buffer_size - a->compressed_buffer_remaining;
1341 a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
1342 a->stream.avail_in = size;
1343 a->stream.next_out = buffer_compressed;
1344 a->stream.avail_out = a->compressed_buffer_remaining;
1346 ret = deflate(&a->stream, Z_FINISH);
1352 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1353 "Failed to compress data");
1354 return (ARCHIVE_FAILED);
1356 } while (ret == Z_OK);
1357 bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1360 * If the compressed size is larger than the original size,
1361 * throw away compressed data, use uncompressed data instead.
1363 if (bytes_compressed > size) {
1364 buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1365 memcpy(buffer_compressed + 1, buff, size);
1366 bytes_compressed = size + 1;
1368 a->compressed_buffer_remaining -= bytes_compressed;
1371 * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
1372 * and the block count in the file is only one, store compressed
1373 * data to decmpfs xattr instead of the resource fork.
1375 if (a->decmpfs_block_count == 1 &&
1376 (a->decmpfs_attr_size + bytes_compressed)
1377 <= MAX_DECMPFS_XATTR_SIZE) {
1378 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1380 memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
1381 buffer_compressed, bytes_compressed);
1382 a->decmpfs_attr_size += bytes_compressed;
1383 a->compressed_buffer_remaining = a->compressed_buffer_size;
1385 * Finish HFS+ Compression.
1386 * - Write the decmpfs xattr.
1387 * - Set the UF_COMPRESSED file flag.
1389 ret = hfs_write_decmpfs(a);
1390 if (ret == ARCHIVE_OK)
1391 ret = hfs_set_compressed_fflag(a);
1395 /* Update block info. */
1396 archive_le32enc(a->decmpfs_block_info++,
1397 a->compressed_rsrc_position_v - RSRC_H_SIZE);
1398 archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
1399 a->compressed_rsrc_position_v += bytes_compressed;
1402 * Write the compressed data to the resource fork.
1404 bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
1405 while (bytes_used >= COMPRESSED_W_SIZE) {
1406 ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
1407 if (ret != ARCHIVE_OK)
1409 bytes_used -= COMPRESSED_W_SIZE;
1410 if (bytes_used > COMPRESSED_W_SIZE)
1411 memmove(a->compressed_buffer,
1412 a->compressed_buffer + COMPRESSED_W_SIZE,
1415 memcpy(a->compressed_buffer,
1416 a->compressed_buffer + COMPRESSED_W_SIZE,
1419 a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1422 * If the current block is the last block, write the remaining
1423 * compressed data and the resource fork footer.
1425 if (a->file_remaining_bytes == 0) {
1429 /* Append the resource footer. */
1430 rsrc_size = hfs_set_resource_fork_footer(
1431 a->compressed_buffer + bytes_used,
1432 a->compressed_buffer_remaining);
1433 ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
1434 a->compressed_buffer_remaining = a->compressed_buffer_size;
1436 /* If the compressed size is not enough smaller than
1437 * the uncompressed size. cancel HFS+ compression.
1438 * TODO: study a behavior of ditto utility and improve
1439 * the condition to fall back into no HFS+ compression. */
1440 bk = HFS_BLOCKS(a->compressed_rsrc_position);
1442 if (bk > HFS_BLOCKS(a->filesize))
1443 return hfs_decompress(a);
1445 * Write the resourcefork header.
1447 if (ret == ARCHIVE_OK)
1448 ret = hfs_write_resource_fork_header(a);
1450 * Finish HFS+ Compression.
1451 * - Write the decmpfs xattr.
1452 * - Set the UF_COMPRESSED file flag.
1454 if (ret == ARCHIVE_OK)
1455 ret = hfs_write_decmpfs(a);
1456 if (ret == ARCHIVE_OK)
1457 ret = hfs_set_compressed_fflag(a);
1463 hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1466 const char *buffer_to_write;
1467 size_t bytes_to_write;
1470 if (a->decmpfs_block_count == (unsigned)-1) {
1473 unsigned int block_count;
1475 if (a->decmpfs_header_p == NULL) {
1476 new_block = malloc(MAX_DECMPFS_XATTR_SIZE
1477 + sizeof(uint32_t));
1478 if (new_block == NULL) {
1479 archive_set_error(&a->archive, ENOMEM,
1480 "Can't allocate memory for decmpfs");
1481 return (ARCHIVE_FATAL);
1483 a->decmpfs_header_p = new_block;
1485 a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1486 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1488 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1490 archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1493 /* Calculate a block count of the file. */
1495 (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1496 MAX_DECMPFS_BLOCK_SIZE;
1498 * Allocate buffer for resource fork.
1499 * Set up related pointers;
1502 RSRC_H_SIZE + /* header */
1503 4 + /* Block count */
1504 (block_count * sizeof(uint32_t) * 2) +
1505 RSRC_F_SIZE; /* footer */
1506 if (new_size > a->resource_fork_allocated_size) {
1507 new_block = realloc(a->resource_fork, new_size);
1508 if (new_block == NULL) {
1509 archive_set_error(&a->archive, ENOMEM,
1510 "Can't allocate memory for ResourceFork");
1511 return (ARCHIVE_FATAL);
1513 a->resource_fork_allocated_size = new_size;
1514 a->resource_fork = new_block;
1517 /* Allocate uncompressed buffer */
1518 if (a->uncompressed_buffer == NULL) {
1519 new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
1520 if (new_block == NULL) {
1521 archive_set_error(&a->archive, ENOMEM,
1522 "Can't allocate memory for decmpfs");
1523 return (ARCHIVE_FATAL);
1525 a->uncompressed_buffer = new_block;
1527 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1528 a->file_remaining_bytes = a->filesize;
1529 a->compressed_buffer_remaining = a->compressed_buffer_size;
1532 * Set up a resource fork.
1534 a->rsrc_xattr_options = XATTR_CREATE;
1535 /* Get the position where we are going to set a bunch
1537 a->decmpfs_block_info =
1538 (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1539 /* Set the block count to the resource fork. */
1540 archive_le32enc(a->decmpfs_block_info++, block_count);
1541 /* Get the position where we are going to set compressed
1543 a->compressed_rsrc_position =
1544 RSRC_H_SIZE + 4 + (block_count * 8);
1545 a->compressed_rsrc_position_v = a->compressed_rsrc_position;
1546 a->decmpfs_block_count = block_count;
1549 /* Ignore redundant bytes. */
1550 if (a->file_remaining_bytes == 0)
1551 return ((ssize_t)size);
1553 /* Do not overrun a block size. */
1554 if (size > a->block_remaining_bytes)
1555 bytes_to_write = a->block_remaining_bytes;
1557 bytes_to_write = size;
1558 /* Do not overrun the file size. */
1559 if (bytes_to_write > a->file_remaining_bytes)
1560 bytes_to_write = a->file_remaining_bytes;
1562 /* For efficiency, if a copy length is full of the uncompressed
1563 * buffer size, do not copy writing data to it. */
1564 if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
1565 buffer_to_write = buff;
1567 memcpy(a->uncompressed_buffer +
1568 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
1569 buff, bytes_to_write);
1570 buffer_to_write = a->uncompressed_buffer;
1572 a->block_remaining_bytes -= bytes_to_write;
1573 a->file_remaining_bytes -= bytes_to_write;
1575 if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
1576 ret = hfs_drive_compressor(a, buffer_to_write,
1577 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
1580 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1582 /* Ignore redundant bytes. */
1583 if (a->file_remaining_bytes == 0)
1584 return ((ssize_t)size);
1585 return (bytes_to_write);
1589 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1592 uint64_t start_size = size;
1593 ssize_t bytes_written = 0;
1594 ssize_t bytes_to_write;
1597 return (ARCHIVE_OK);
1599 if (a->filesize == 0 || a->fd < 0) {
1600 archive_set_error(&a->archive, 0,
1601 "Attempt to write to an empty file");
1602 return (ARCHIVE_WARN);
1605 /* If this write would run beyond the file size, truncate it. */
1606 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
1607 start_size = size = (size_t)(a->filesize - a->offset);
1609 /* Write the data. */
1611 bytes_to_write = size;
1612 /* Seek if necessary to the specified offset. */
1613 if (a->offset < a->fd_offset) {
1614 /* Can't support backward move. */
1615 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1617 return (ARCHIVE_FATAL);
1618 } else if (a->offset > a->fd_offset) {
1619 int64_t skip = a->offset - a->fd_offset;
1620 char nullblock[1024];
1622 memset(nullblock, 0, sizeof(nullblock));
1624 if (skip > (int64_t)sizeof(nullblock))
1625 bytes_written = hfs_write_decmpfs_block(
1626 a, nullblock, sizeof(nullblock));
1628 bytes_written = hfs_write_decmpfs_block(
1629 a, nullblock, skip);
1630 if (bytes_written < 0) {
1631 archive_set_error(&a->archive, errno,
1633 return (ARCHIVE_WARN);
1635 skip -= bytes_written;
1638 a->fd_offset = a->offset;
1641 hfs_write_decmpfs_block(a, buff, bytes_to_write);
1642 if (bytes_written < 0)
1643 return (bytes_written);
1644 buff += bytes_written;
1645 size -= bytes_written;
1646 a->total_bytes_written += bytes_written;
1647 a->offset += bytes_written;
1648 a->fd_offset = a->offset;
1650 return (start_size - size);
1654 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1657 return (write_data_block(a, buff, size));
1662 _archive_write_disk_data_block(struct archive *_a,
1663 const void *buff, size_t size, int64_t offset)
1665 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1668 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1669 ARCHIVE_STATE_DATA, "archive_write_data_block");
1672 if (a->todo & TODO_HFS_COMPRESSION)
1673 r = hfs_write_data_block(a, buff, size);
1675 r = write_data_block(a, buff, size);
1678 if ((size_t)r < size) {
1679 archive_set_error(&a->archive, 0,
1680 "Too much data: Truncating file at %ju bytes",
1681 (uintmax_t)a->filesize);
1682 return (ARCHIVE_WARN);
1684 #if ARCHIVE_VERSION_NUMBER < 3999000
1685 return (ARCHIVE_OK);
1692 _archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1694 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1696 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1697 ARCHIVE_STATE_DATA, "archive_write_data");
1699 if (a->todo & TODO_HFS_COMPRESSION)
1700 return (hfs_write_data_block(a, buff, size));
1701 return (write_data_block(a, buff, size));
1705 _archive_write_disk_finish_entry(struct archive *_a)
1707 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1708 int ret = ARCHIVE_OK;
1710 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1711 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1712 "archive_write_finish_entry");
1713 if (a->archive.state & ARCHIVE_STATE_HEADER)
1714 return (ARCHIVE_OK);
1715 archive_clear_error(&a->archive);
1717 /* Pad or truncate file to the right size. */
1719 /* There's no file. */
1720 } else if (a->filesize < 0) {
1721 /* File size is unknown, so we can't set the size. */
1722 } else if (a->fd_offset == a->filesize) {
1723 /* Last write ended at exactly the filesize; we're done. */
1724 /* Hopefully, this is the common case. */
1725 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
1726 } else if (a->todo & TODO_HFS_COMPRESSION) {
1730 if (a->file_remaining_bytes)
1731 memset(null_d, 0, sizeof(null_d));
1732 while (a->file_remaining_bytes) {
1733 if (a->file_remaining_bytes > sizeof(null_d))
1734 r = hfs_write_data_block(
1735 a, null_d, sizeof(null_d));
1737 r = hfs_write_data_block(
1738 a, null_d, a->file_remaining_bytes);
1745 if (ftruncate(a->fd, a->filesize) == -1 &&
1747 archive_set_error(&a->archive, errno,
1748 "File size could not be restored");
1749 return (ARCHIVE_FAILED);
1753 * Not all platforms implement the XSI option to
1754 * extend files via ftruncate. Stat() the file again
1755 * to see what happened.
1758 if ((ret = lazy_stat(a)) != ARCHIVE_OK)
1760 /* We can use lseek()/write() to extend the file if
1761 * ftruncate didn't work or isn't available. */
1762 if (a->st.st_size < a->filesize) {
1763 const char nul = '\0';
1764 if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
1765 archive_set_error(&a->archive, errno,
1767 return (ARCHIVE_FATAL);
1769 if (write(a->fd, &nul, 1) < 0) {
1770 archive_set_error(&a->archive, errno,
1771 "Write to restore size failed");
1772 return (ARCHIVE_FATAL);
1778 /* Restore metadata. */
1781 * This is specific to Mac OS X.
1782 * If the current file is an AppleDouble file, it should be
1783 * linked with the data fork file and remove it.
1785 if (a->todo & TODO_APPLEDOUBLE) {
1786 int r2 = fixup_appledouble(a, a->name);
1787 if (r2 == ARCHIVE_EOF) {
1788 /* The current file has been successfully linked
1789 * with the data fork file and removed. So there
1790 * is nothing to do on the current file. */
1791 goto finish_metadata;
1793 if (r2 < ret) ret = r2;
1797 * Look up the "real" UID only if we're going to need it.
1798 * TODO: the TODO_SGID condition can be dropped here, can't it?
1800 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
1801 a->uid = archive_write_disk_uid(&a->archive,
1802 archive_entry_uname(a->entry),
1803 archive_entry_uid(a->entry));
1805 /* Look up the "real" GID only if we're going to need it. */
1806 /* TODO: the TODO_SUID condition can be dropped here, can't it? */
1807 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
1808 a->gid = archive_write_disk_gid(&a->archive,
1809 archive_entry_gname(a->entry),
1810 archive_entry_gid(a->entry));
1814 * Restore ownership before set_mode tries to restore suid/sgid
1815 * bits. If we set the owner, we know what it is and can skip
1816 * a stat() call to examine the ownership of the file on disk.
1818 if (a->todo & TODO_OWNER) {
1819 int r2 = set_ownership(a);
1820 if (r2 < ret) ret = r2;
1825 * If we're not root, we won't be setting any security
1826 * attributes that may be wiped by the set_mode() routine
1827 * below. We also can't set xattr on non-owner-writable files,
1828 * which may be the state after set_mode(). Perform
1829 * set_xattrs() first based on these constraints.
1831 if (a->user_uid != 0 &&
1832 (a->todo & TODO_XATTR)) {
1833 int r2 = set_xattrs(a);
1834 if (r2 < ret) ret = r2;
1838 * set_mode must precede ACLs on systems such as Solaris and
1839 * FreeBSD where setting the mode implicitly clears extended ACLs
1841 if (a->todo & TODO_MODE) {
1842 int r2 = set_mode(a, a->mode);
1843 if (r2 < ret) ret = r2;
1847 * Security-related extended attributes (such as
1848 * security.capability on Linux) have to be restored last,
1849 * since they're implicitly removed by other file changes.
1850 * We do this last only when root.
1852 if (a->user_uid == 0 &&
1853 (a->todo & TODO_XATTR)) {
1854 int r2 = set_xattrs(a);
1855 if (r2 < ret) ret = r2;
1859 * Some flags prevent file modification; they must be restored after
1860 * file contents are written.
1862 if (a->todo & TODO_FFLAGS) {
1863 int r2 = set_fflags(a);
1864 if (r2 < ret) ret = r2;
1868 * Time must follow most other metadata;
1869 * otherwise atime will get changed.
1871 if (a->todo & TODO_TIMES) {
1872 int r2 = set_times_from_entry(a);
1873 if (r2 < ret) ret = r2;
1877 * Mac extended metadata includes ACLs.
1879 if (a->todo & TODO_MAC_METADATA) {
1880 const void *metadata;
1881 size_t metadata_size;
1882 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
1883 if (metadata != NULL && metadata_size > 0) {
1884 int r2 = set_mac_metadata(a, archive_entry_pathname(
1885 a->entry), metadata, metadata_size);
1886 if (r2 < ret) ret = r2;
1891 * ACLs must be restored after timestamps because there are
1892 * ACLs that prevent attribute changes (including time).
1894 if (a->todo & TODO_ACLS) {
1896 r2 = archive_write_disk_set_acls(&a->archive, a->fd,
1897 archive_entry_pathname(a->entry),
1898 archive_entry_acl(a->entry),
1899 archive_entry_mode(a->entry));
1900 if (r2 < ret) ret = r2;
1904 /* If there's an fd, we can close it now. */
1909 if (rename(a->tmpname, a->name) == -1) {
1910 archive_set_error(&a->archive, errno,
1911 "Failed to rename temporary file");
1912 ret = ARCHIVE_FAILED;
1918 /* If there's an entry, we can release it now. */
1919 archive_entry_free(a->entry);
1921 a->archive.state = ARCHIVE_STATE_HEADER;
1926 archive_write_disk_set_group_lookup(struct archive *_a,
1928 la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1929 void (*cleanup_gid)(void *private))
1931 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1932 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1933 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
1935 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1936 (a->cleanup_gid)(a->lookup_gid_data);
1938 a->lookup_gid = lookup_gid;
1939 a->cleanup_gid = cleanup_gid;
1940 a->lookup_gid_data = private_data;
1941 return (ARCHIVE_OK);
1945 archive_write_disk_set_user_lookup(struct archive *_a,
1947 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1948 void (*cleanup_uid)(void *private))
1950 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1951 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1952 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
1954 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1955 (a->cleanup_uid)(a->lookup_uid_data);
1957 a->lookup_uid = lookup_uid;
1958 a->cleanup_uid = cleanup_uid;
1959 a->lookup_uid_data = private_data;
1960 return (ARCHIVE_OK);
1964 archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1966 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1967 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1968 ARCHIVE_STATE_ANY, "archive_write_disk_gid");
1970 return (a->lookup_gid)(a->lookup_gid_data, name, id);
1975 archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1977 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1978 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1979 ARCHIVE_STATE_ANY, "archive_write_disk_uid");
1981 return (a->lookup_uid)(a->lookup_uid_data, name, id);
1986 * Create a new archive_write_disk object and initialize it with global state.
1989 archive_write_disk_new(void)
1991 struct archive_write_disk *a;
1993 a = (struct archive_write_disk *)calloc(1, sizeof(*a));
1996 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
1997 /* We're ready to write a header immediately. */
1998 a->archive.state = ARCHIVE_STATE_HEADER;
1999 a->archive.vtable = archive_write_disk_vtable();
2000 a->start_time = time(NULL);
2001 /* Query and restore the umask. */
2002 umask(a->user_umask = umask(0));
2004 a->user_uid = geteuid();
2005 #endif /* HAVE_GETEUID */
2006 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
2011 a->decmpfs_compression_level = 5;
2013 return (&a->archive);
2018 * If pathname is longer than PATH_MAX, chdir to a suitable
2019 * intermediate dir and edit the path down to a shorter suffix. Note
2020 * that this routine never returns an error; if the chdir() attempt
2021 * fails for any reason, we just go ahead with the long pathname. The
2022 * object creation is likely to fail, but any error will get handled
2025 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
2027 edit_deep_directories(struct archive_write_disk *a)
2030 char *tail = a->name;
2032 /* If path is short, avoid the open() below. */
2033 if (strlen(tail) < PATH_MAX)
2036 /* Try to record our starting dir. */
2037 a->restore_pwd = la_opendirat(AT_FDCWD, ".");
2038 __archive_ensure_cloexec_flag(a->restore_pwd);
2039 if (a->restore_pwd < 0)
2042 /* As long as the path is too long... */
2043 while (strlen(tail) >= PATH_MAX) {
2044 /* Locate a dir prefix shorter than PATH_MAX. */
2045 tail += PATH_MAX - 8;
2046 while (tail > a->name && *tail != '/')
2048 /* Exit if we find a too-long path component. */
2049 if (tail <= a->name)
2051 /* Create the intermediate dir and chdir to it. */
2052 *tail = '\0'; /* Terminate dir portion */
2053 ret = create_dir(a, a->name);
2054 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
2055 ret = ARCHIVE_FAILED;
2056 *tail = '/'; /* Restore the / we removed. */
2057 if (ret != ARCHIVE_OK)
2060 /* The chdir() succeeded; we've now shortened the path. */
2068 * The main restore function.
2071 restore_entry(struct archive_write_disk *a)
2073 int ret = ARCHIVE_OK, en;
2075 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
2077 * TODO: Fix this. Apparently, there are platforms
2078 * that still allow root to hose the entire filesystem
2079 * by unlinking a dir. The S_ISDIR() test above
2080 * prevents us from using unlink() here if the new
2081 * object is a dir, but that doesn't mean the old
2082 * object isn't a dir.
2084 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2085 (void)clear_nochange_fflags(a);
2086 if (unlink(a->name) == 0) {
2087 /* We removed it, reset cached stat. */
2089 } else if (errno == ENOENT) {
2090 /* File didn't exist, that's just as good. */
2091 } else if (rmdir(a->name) == 0) {
2092 /* It was a dir, but now it's gone. */
2095 /* We tried, but couldn't get rid of it. */
2096 archive_set_error(&a->archive, errno,
2097 "Could not unlink");
2098 return(ARCHIVE_FAILED);
2102 /* Try creating it first; if this fails, we'll try to recover. */
2103 en = create_filesystem_object(a);
2105 if ((en == ENOTDIR || en == ENOENT)
2106 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
2107 /* If the parent dir doesn't exist, try creating it. */
2108 create_parent_dir(a, a->name);
2109 /* Now try to create the object again. */
2110 en = create_filesystem_object(a);
2113 if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
2114 archive_set_error(&a->archive, en,
2115 "Hard-link target '%s' does not exist.",
2116 archive_entry_hardlink(a->entry));
2117 return (ARCHIVE_FAILED);
2120 if ((en == EISDIR || en == EEXIST)
2121 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2122 /* If we're not overwriting, we're done. */
2123 if (S_ISDIR(a->mode)) {
2124 /* Don't overwrite any settings on existing directories. */
2127 archive_entry_unset_size(a->entry);
2128 return (ARCHIVE_OK);
2132 * Some platforms return EISDIR if you call
2133 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
2134 * return EEXIST. POSIX is ambiguous, requiring EISDIR
2135 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
2136 * on an existing item.
2139 /* A dir is in the way of a non-dir, rmdir it. */
2140 if (rmdir(a->name) != 0) {
2141 archive_set_error(&a->archive, errno,
2142 "Can't remove already-existing dir");
2143 return (ARCHIVE_FAILED);
2147 en = create_filesystem_object(a);
2148 } else if (en == EEXIST) {
2150 * We know something is in the way, but we don't know what;
2151 * we need to find out before we go any further.
2155 * The SECURE_SYMLINKS logic has already removed a
2156 * symlink to a dir if the client wants that. So
2157 * follow the symlink if we're creating a dir.
2159 if (S_ISDIR(a->mode))
2160 r = la_stat(a->name, &a->st);
2162 * If it's not a dir (or it's a broken symlink),
2163 * then don't follow it.
2165 if (r != 0 || !S_ISDIR(a->mode))
2166 r = lstat(a->name, &a->st);
2168 archive_set_error(&a->archive, errno,
2169 "Can't stat existing object");
2170 return (ARCHIVE_FAILED);
2174 * NO_OVERWRITE_NEWER doesn't apply to directories.
2176 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
2177 && !S_ISDIR(a->st.st_mode)) {
2178 if (!older(&(a->st), a->entry)) {
2179 archive_entry_unset_size(a->entry);
2180 return (ARCHIVE_OK);
2184 /* If it's our archive, we're done. */
2185 if (a->skip_file_set &&
2186 a->st.st_dev == (dev_t)a->skip_file_dev &&
2187 a->st.st_ino == (ino_t)a->skip_file_ino) {
2188 archive_set_error(&a->archive, 0,
2189 "Refusing to overwrite archive");
2190 return (ARCHIVE_FAILED);
2193 if (!S_ISDIR(a->st.st_mode)) {
2194 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2195 (void)clear_nochange_fflags(a);
2197 if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) &&
2198 S_ISREG(a->st.st_mode)) {
2199 /* Use a temporary file to extract */
2200 if ((a->fd = la_mktemp(a)) == -1) {
2201 archive_set_error(&a->archive, errno,
2202 "Can't create temporary file");
2203 return ARCHIVE_FAILED;
2208 /* A non-dir is in the way, unlink it. */
2209 if (unlink(a->name) != 0) {
2210 archive_set_error(&a->archive, errno,
2211 "Can't unlink already-existing "
2213 return (ARCHIVE_FAILED);
2217 en = create_filesystem_object(a);
2219 } else if (!S_ISDIR(a->mode)) {
2220 /* A dir is in the way of a non-dir, rmdir it. */
2221 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2222 (void)clear_nochange_fflags(a);
2223 if (rmdir(a->name) != 0) {
2224 archive_set_error(&a->archive, errno,
2225 "Can't replace existing directory with non-directory");
2226 return (ARCHIVE_FAILED);
2229 en = create_filesystem_object(a);
2232 * There's a dir in the way of a dir. Don't
2233 * waste time with rmdir()/mkdir(), just fix
2234 * up the permissions on the existing dir.
2235 * Note that we don't change perms on existing
2236 * dirs unless _EXTRACT_PERM is specified.
2238 if ((a->mode != a->st.st_mode)
2239 && (a->todo & TODO_MODE_FORCE))
2240 a->deferred |= (a->todo & TODO_MODE);
2241 /* Ownership doesn't need deferred fixup. */
2242 en = 0; /* Forget the EEXIST. */
2247 /* Everything failed; give up here. */
2248 if ((&a->archive)->error == NULL)
2249 archive_set_error(&a->archive, en, "Can't create '%s'",
2251 return (ARCHIVE_FAILED);
2254 a->pst = NULL; /* Cached stat data no longer valid. */
2259 * Returns 0 if creation succeeds, or else returns errno value from
2260 * the failed system call. Note: This function should only ever perform
2261 * a single system call.
2264 create_filesystem_object(struct archive_write_disk *a)
2266 /* Create the entry. */
2267 const char *linkname;
2268 mode_t final_mode, mode;
2270 /* these for check_symlinks_fsobj */
2271 char *linkname_copy; /* non-const copy of linkname */
2273 struct archive_string error_string;
2276 /* We identify hard/symlinks according to the link names. */
2277 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
2278 linkname = archive_entry_hardlink(a->entry);
2279 if (linkname != NULL) {
2283 archive_string_init(&error_string);
2284 linkname_copy = strdup(linkname);
2285 if (linkname_copy == NULL) {
2289 * TODO: consider using the cleaned-up path as the link
2292 r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2293 &error_string, a->flags);
2294 if (r != ARCHIVE_OK) {
2295 archive_set_error(&a->archive, error_number, "%s",
2297 free(linkname_copy);
2298 archive_string_free(&error_string);
2300 * EPERM is more appropriate than error_number for our
2305 r = check_symlinks_fsobj(linkname_copy, &error_number,
2306 &error_string, a->flags, 1);
2307 if (r != ARCHIVE_OK) {
2308 archive_set_error(&a->archive, error_number, "%s",
2310 free(linkname_copy);
2311 archive_string_free(&error_string);
2313 * EPERM is more appropriate than error_number for our
2318 free(linkname_copy);
2319 archive_string_free(&error_string);
2321 * Unlinking and linking here is really not atomic,
2322 * but doing it right, would require us to construct
2323 * an mktemplink() function, and then use rename(2).
2325 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2328 r = linkat(AT_FDCWD, linkname, AT_FDCWD, a->name,
2331 r = link(linkname, a->name) ? errno : 0;
2334 * New cpio and pax formats allow hardlink entries
2335 * to carry data, so we may have to open the file
2336 * for hardlink entries.
2338 * If the hardlink was successfully created and
2339 * the archive doesn't have carry data for it,
2340 * consider it to be non-authoritative for meta data.
2341 * This is consistent with GNU tar and BSD pax.
2342 * If the hardlink does carry data, let the last
2343 * archive entry decide ownership.
2345 if (r == 0 && a->filesize <= 0) {
2348 } else if (r == 0 && a->filesize > 0) {
2350 r = lstat(a->name, &st);
2352 r = la_stat(a->name, &st);
2356 else if ((st.st_mode & AE_IFMT) == AE_IFREG) {
2357 a->fd = open(a->name, O_WRONLY | O_TRUNC |
2358 O_BINARY | O_CLOEXEC | O_NOFOLLOW);
2359 __archive_ensure_cloexec_flag(a->fd);
2367 linkname = archive_entry_symlink(a->entry);
2368 if (linkname != NULL) {
2371 * Unlinking and linking here is really not atomic,
2372 * but doing it right, would require us to construct
2373 * an mktempsymlink() function, and then use rename(2).
2375 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2377 return symlink(linkname, a->name) ? errno : 0;
2384 * The remaining system calls all set permissions, so let's
2385 * try to take advantage of that to avoid an extra chmod()
2386 * call. (Recall that umask is set to zero right now!)
2389 /* Mode we want for the final restored object (w/o file type bits). */
2390 final_mode = a->mode & 07777;
2392 * The mode that will actually be restored in this step. Note
2393 * that SUID, SGID, etc, require additional work to ensure
2394 * security, so we never restore them at this point.
2396 mode = final_mode & 0777 & ~a->user_umask;
2399 * Always create writable such that [f]setxattr() works if we're not
2402 if (a->user_uid != 0 &&
2403 a->todo & (TODO_HFS_COMPRESSION | TODO_XATTR)) {
2407 switch (a->mode & AE_IFMT) {
2409 /* POSIX requires that we fall through here. */
2413 a->fd = open(a->name,
2414 O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2415 __archive_ensure_cloexec_flag(a->fd);
2420 /* Note: we use AE_IFCHR for the case label, and
2421 * S_IFCHR for the mknod() call. This is correct. */
2422 r = mknod(a->name, mode | S_IFCHR,
2423 archive_entry_rdev(a->entry));
2426 /* TODO: Find a better way to warn about our inability
2427 * to restore a char device node. */
2429 #endif /* HAVE_MKNOD */
2432 r = mknod(a->name, mode | S_IFBLK,
2433 archive_entry_rdev(a->entry));
2436 /* TODO: Find a better way to warn about our inability
2437 * to restore a block device node. */
2439 #endif /* HAVE_MKNOD */
2441 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2442 r = mkdir(a->name, mode);
2444 /* Defer setting dir times. */
2445 a->deferred |= (a->todo & TODO_TIMES);
2446 a->todo &= ~TODO_TIMES;
2447 /* Never use an immediate chmod(). */
2448 /* We can't avoid the chmod() entirely if EXTRACT_PERM
2449 * because of SysV SGID inheritance. */
2450 if ((mode != final_mode)
2451 || (a->flags & ARCHIVE_EXTRACT_PERM))
2452 a->deferred |= (a->todo & TODO_MODE);
2453 a->todo &= ~TODO_MODE;
2458 r = mkfifo(a->name, mode);
2461 /* TODO: Find a better way to warn about our inability
2462 * to restore a fifo. */
2464 #endif /* HAVE_MKFIFO */
2467 /* All the system calls above set errno on failure. */
2471 /* If we managed to set the final mode, we've avoided a chmod(). */
2472 if (mode == final_mode)
2473 a->todo &= ~TODO_MODE;
2478 * Cleanup function for archive_extract. Mostly, this involves processing
2479 * the fixup list, which is used to address a number of problems:
2480 * * Dir permissions might prevent us from restoring a file in that
2481 * dir, so we restore the dir with minimum 0700 permissions first,
2482 * then correct the mode at the end.
2483 * * Similarly, the act of restoring a file touches the directory
2484 * and changes the timestamp on the dir, so we have to touch-up dir
2485 * timestamps at the end as well.
2486 * * Some file flags can interfere with the restore by, for example,
2487 * preventing the creation of hardlinks to those files.
2488 * * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2490 * Note that tar/cpio do not require that archives be in a particular
2491 * order; there is no way to know when the last file has been restored
2492 * within a directory, so there's no way to optimize the memory usage
2493 * here by fixing up the directory any earlier than the
2496 * XXX TODO: Directory ACLs should be restored here, for the same
2497 * reason we set directory perms here. XXX
2500 _archive_write_disk_close(struct archive *_a)
2502 struct archive_write_disk *a = (struct archive_write_disk *)_a;
2503 struct fixup_entry *next, *p;
2506 int fd, ret, openflags;
2508 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2509 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2510 "archive_write_disk_close");
2511 ret = _archive_write_disk_finish_entry(&a->archive);
2513 /* Sort dir list so directories are fixed up in depth-first order. */
2514 p = sort_dir_list(a->fixup_list);
2518 a->pst = NULL; /* Mark stat cache as out-of-date. */
2520 /* We must strip trailing slashes from the path to avoid
2521 dereferencing symbolic links to directories */
2525 while (c != p->name && *(c - 1) == '/') {
2531 goto skip_fixup_entry;
2534 * We need to verify if the type of the file
2535 * we are going to open matches the file type
2536 * of the fixup entry.
2538 openflags = O_BINARY | O_NOFOLLOW | O_RDONLY
2540 #if defined(O_DIRECTORY)
2541 if (p->filetype == AE_IFDIR)
2542 openflags |= O_DIRECTORY;
2544 fd = open(p->name, openflags);
2546 #if defined(O_DIRECTORY)
2548 * If we support O_DIRECTORY and open was
2549 * successful we can skip the file type check
2550 * for directories. For other file types
2551 * we need to verify via fstat() or lstat()
2553 if (fd == -1 || p->filetype != AE_IFDIR) {
2556 fstat(fd, &st) != 0 ||
2557 la_verify_filetype(st.st_mode,
2558 p->filetype) == 0)) {
2559 goto skip_fixup_entry;
2562 if (lstat(p->name, &st) != 0 ||
2563 la_verify_filetype(st.st_mode,
2564 p->filetype) == 0) {
2565 goto skip_fixup_entry;
2571 fstat(fd, &st) != 0 ||
2572 la_verify_filetype(st.st_mode,
2573 p->filetype) == 0)) {
2574 goto skip_fixup_entry;
2577 if (lstat(p->name, &st) != 0 ||
2578 la_verify_filetype(st.st_mode,
2579 p->filetype) == 0) {
2580 goto skip_fixup_entry;
2584 if (p->fixup & TODO_TIMES) {
2585 set_times(a, fd, p->mode, p->name,
2586 p->atime, p->atime_nanos,
2587 p->birthtime, p->birthtime_nanos,
2588 p->mtime, p->mtime_nanos,
2589 p->ctime, p->ctime_nanos);
2591 if (p->fixup & TODO_MODE_BASE) {
2594 fchmod(fd, p->mode & 07777);
2598 lchmod(p->name, p->mode & 07777);
2600 chmod(p->name, p->mode & 07777);
2603 if (p->fixup & TODO_ACLS)
2604 archive_write_disk_set_acls(&a->archive, fd,
2605 p->name, &p->acl, p->mode);
2606 if (p->fixup & TODO_FFLAGS)
2607 set_fflags_platform(a, fd, p->name,
2608 p->mode, p->fflags_set, 0);
2609 if (p->fixup & TODO_MAC_METADATA)
2610 set_mac_metadata(a, p->name, p->mac_metadata,
2611 p->mac_metadata_size);
2614 archive_acl_clear(&p->acl);
2615 free(p->mac_metadata);
2622 a->fixup_list = NULL;
2627 _archive_write_disk_free(struct archive *_a)
2629 struct archive_write_disk *a;
2632 return (ARCHIVE_OK);
2633 archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2634 ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2635 a = (struct archive_write_disk *)_a;
2636 ret = _archive_write_disk_close(&a->archive);
2637 archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2638 archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2639 archive_entry_free(a->entry);
2640 archive_string_free(&a->_name_data);
2641 archive_string_free(&a->_tmpname_data);
2642 archive_string_free(&a->archive.error_string);
2643 archive_string_free(&a->path_safe);
2644 a->archive.magic = 0;
2645 __archive_clean(&a->archive);
2646 free(a->decmpfs_header_p);
2647 free(a->resource_fork);
2648 free(a->compressed_buffer);
2649 free(a->uncompressed_buffer);
2650 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2651 && defined(HAVE_ZLIB_H)
2652 if (a->stream_valid) {
2653 switch (deflateEnd(&a->stream)) {
2657 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2658 "Failed to clean up compressor");
2659 ret = ARCHIVE_FATAL;
2669 * Simple O(n log n) merge sort to order the fixup list. In
2670 * particular, we want to restore dir timestamps depth-first.
2672 static struct fixup_entry *
2673 sort_dir_list(struct fixup_entry *p)
2675 struct fixup_entry *a, *b, *t;
2679 /* A one-item list is already sorted. */
2680 if (p->next == NULL)
2683 /* Step 1: split the list. */
2687 /* Step a twice, t once. */
2693 /* Now, t is at the mid-point, so break the list here. */
2698 /* Step 2: Recursively sort the two sub-lists. */
2699 a = sort_dir_list(a);
2700 b = sort_dir_list(b);
2702 /* Step 3: Merge the returned lists. */
2703 /* Pick the first element for the merged list. */
2704 if (strcmp(a->name, b->name) > 0) {
2712 /* Always put the later element on the list first. */
2713 while (a != NULL && b != NULL) {
2714 if (strcmp(a->name, b->name) > 0) {
2724 /* Only one list is non-empty, so just splice it on. */
2734 * Returns a new, initialized fixup entry.
2736 * TODO: Reduce the memory requirements for this list by using a tree
2737 * structure rather than a simple list of names.
2739 static struct fixup_entry *
2740 new_fixup(struct archive_write_disk *a, const char *pathname)
2742 struct fixup_entry *fe;
2744 fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2746 archive_set_error(&a->archive, ENOMEM,
2747 "Can't allocate memory for a fixup");
2750 fe->next = a->fixup_list;
2754 fe->name = strdup(pathname);
2759 * Returns a fixup structure for the current entry.
2761 static struct fixup_entry *
2762 current_fixup(struct archive_write_disk *a, const char *pathname)
2764 if (a->current_fixup == NULL)
2765 a->current_fixup = new_fixup(a, pathname);
2766 return (a->current_fixup);
2769 /* Error helper for new *_fsobj functions */
2771 fsobj_error(int *a_eno, struct archive_string *a_estr,
2772 int err, const char *errstr, const char *path)
2777 archive_string_sprintf(a_estr, "%s%s", errstr, path);
2781 * TODO: Someday, integrate this with the deep dir support; they both
2782 * scan the path and both can be optimized by comparing against other
2786 * Checks the given path to see if any elements along it are symlinks. Returns
2787 * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2790 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2791 int flags, int checking_linkname)
2793 #if !defined(HAVE_LSTAT) && \
2794 !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT))
2795 /* Platform doesn't have lstat, so we can't look for symlinks. */
2796 (void)path; /* UNUSED */
2797 (void)error_number; /* UNUSED */
2798 (void)error_string; /* UNUSED */
2799 (void)flags; /* UNUSED */
2800 (void)checking_linkname; /* UNUSED */
2801 return (ARCHIVE_OK);
2803 int res = ARCHIVE_OK;
2811 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2815 /* Nothing to do here if name is empty */
2817 return (ARCHIVE_OK);
2820 * Guard against symlink tricks. Reject any archive entry whose
2821 * destination would be altered by a symlink.
2823 * Walk the filename in chunks separated by '/'. For each segment:
2824 * - if it doesn't exist, continue
2825 * - if it's symlink, abort or remove it
2826 * - if it's a directory and it's not the last chunk, cd into it
2828 * head points to the current (relative) path
2829 * tail points to the temporary \0 terminating the segment we're
2830 * currently examining
2831 * c holds what used to be in *tail
2832 * last is 1 if this is the last tail
2834 chdir_fd = la_opendirat(AT_FDCWD, ".");
2835 __archive_ensure_cloexec_flag(chdir_fd);
2837 fsobj_error(a_eno, a_estr, errno,
2838 "Could not open ", path);
2839 return (ARCHIVE_FATAL);
2844 /* TODO: reintroduce a safe cache here? */
2845 /* Skip the root directory if the path is absolute. */
2846 if(tail == path && tail[0] == '/')
2848 /* Keep going until we've checked the entire name.
2849 * head, tail, path all alias the same string, which is
2850 * temporarily zeroed at tail, so be careful restoring the
2851 * stashed (c=tail[0]) for error messages.
2852 * Exiting the loop with break is okay; continue is not.
2856 * Skip the separator we just consumed, plus any adjacent ones
2858 while (*tail == '/')
2860 /* Skip the next path element. */
2861 while (*tail != '\0' && *tail != '/')
2863 /* is this the last path component? */
2864 last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2865 /* temporarily truncate the string here */
2868 /* Check that we haven't hit a symlink. */
2869 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2870 r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW);
2872 r = lstat(head, &st);
2876 /* We've hit a dir that doesn't exist; stop now. */
2877 if (errno == ENOENT) {
2881 * Treat any other error as fatal - best to be
2883 * Note: This effectively disables deep
2884 * directory support when security checks are
2885 * enabled. Otherwise, very long pathnames that
2886 * trigger an error here could evade the
2888 * TODO: We could do better, but it would
2889 * probably require merging the symlink checks
2890 * with the deep-directory editing.
2892 fsobj_error(a_eno, a_estr, errno,
2893 "Could not stat ", path);
2894 res = ARCHIVE_FAILED;
2897 } else if (S_ISDIR(st.st_mode)) {
2899 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2900 fd = la_opendirat(chdir_fd, head);
2913 fsobj_error(a_eno, a_estr, errno,
2914 "Could not chdir ", path);
2915 res = (ARCHIVE_FATAL);
2918 /* Our view is now from inside this dir: */
2921 } else if (S_ISLNK(st.st_mode)) {
2922 if (last && checking_linkname) {
2925 * Hardlinks to symlinks are safe to write
2926 * if linkat() is supported as it does not
2932 * We return ARCHIVE_FAILED here as we are
2933 * not able to safely write hardlinks
2937 fsobj_error(a_eno, a_estr, errno,
2938 "Cannot write hardlink to symlink ",
2940 res = ARCHIVE_FAILED;
2946 * Last element is symlink; remove it
2947 * so we can overwrite it with the
2948 * item being extracted.
2950 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2951 r = unlinkat(chdir_fd, head, 0);
2957 fsobj_error(a_eno, a_estr, errno,
2958 "Could not remove symlink ",
2960 res = ARCHIVE_FAILED;
2964 * Even if we did remove it, a warning
2965 * is in order. The warning is silly,
2966 * though, if we're just replacing one
2967 * symlink with another symlink.
2971 * FIXME: not sure how important this is to
2975 if (!S_ISLNK(path)) {
2976 fsobj_error(a_eno, a_estr, 0,
2977 "Removing symlink ", path);
2980 /* Symlink gone. No more problem! */
2983 } else if (flags & ARCHIVE_EXTRACT_UNLINK) {
2984 /* User asked us to remove problems. */
2985 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2986 r = unlinkat(chdir_fd, head, 0);
2992 fsobj_error(a_eno, a_estr, 0,
2993 "Cannot remove intervening "
2995 res = ARCHIVE_FAILED;
3000 ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
3002 * We are not the last element and we want to
3003 * follow symlinks if they are a directory.
3005 * This is needed to extract hardlinks over
3008 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3009 r = fstatat(chdir_fd, head, &st, 0);
3011 r = la_stat(head, &st);
3015 if (errno == ENOENT) {
3018 fsobj_error(a_eno, a_estr,
3020 "Could not stat ", path);
3021 res = (ARCHIVE_FAILED);
3024 } else if (S_ISDIR(st.st_mode)) {
3025 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3026 fd = la_opendirat(chdir_fd, head);
3039 fsobj_error(a_eno, a_estr,
3041 "Could not chdir ", path);
3042 res = (ARCHIVE_FATAL);
3046 * Our view is now from inside
3052 fsobj_error(a_eno, a_estr, 0,
3053 "Cannot extract through "
3055 res = ARCHIVE_FAILED;
3060 fsobj_error(a_eno, a_estr, 0,
3061 "Cannot extract through symlink ", path);
3062 res = ARCHIVE_FAILED;
3066 /* be sure to always maintain this */
3068 if (tail[0] != '\0')
3069 tail++; /* Advance to the next segment. */
3071 /* Catches loop exits via break */
3073 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3074 /* If we operate with openat(), fstatat() and unlinkat() there was
3075 * no chdir(), so just close the fd */
3079 /* If we changed directory above, restore it here. */
3080 if (chdir_fd >= 0) {
3081 r = fchdir(chdir_fd);
3083 fsobj_error(a_eno, a_estr, errno,
3084 "chdir() failure", "");
3089 res = (ARCHIVE_FATAL);
3093 /* TODO: reintroduce a safe cache here? */
3099 * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
3100 * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
3103 check_symlinks(struct archive_write_disk *a)
3105 struct archive_string error_string;
3108 archive_string_init(&error_string);
3109 rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
3111 if (rc != ARCHIVE_OK) {
3112 archive_set_error(&a->archive, error_number, "%s",
3115 archive_string_free(&error_string);
3116 a->pst = NULL; /* to be safe */
3121 #if defined(__CYGWIN__)
3123 * 1. Convert a path separator from '\' to '/' .
3124 * We shouldn't check multibyte character directly because some
3125 * character-set have been using the '\' character for a part of
3126 * its multibyte character code.
3127 * 2. Replace unusable characters in Windows with underscore('_').
3128 * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
3131 cleanup_pathname_win(char *path)
3136 int mb, complete, utf8;
3141 utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
3142 for (p = path; *p != '\0'; p++) {
3145 /* If previous byte is smaller than 128,
3146 * this is not second byte of multibyte characters,
3147 * so we can replace '\' with '/'. */
3151 complete = 0;/* uncompleted. */
3152 } else if (*(unsigned char *)p > 127)
3156 /* Rewrite the path name if its next character is unusable. */
3157 if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
3158 *p == '<' || *p == '>' || *p == '|')
3165 * Convert path separator in wide-character.
3168 while (*p != '\0' && alen) {
3169 l = mbtowc(&wc, p, alen);
3170 if (l == (size_t)-1) {
3171 while (*p != '\0') {
3178 if (l == 1 && wc == L'\\')
3187 * Canonicalize the pathname. In particular, this strips duplicate
3188 * '/' characters, '.' elements, and trailing '/'. It also raises an
3189 * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
3190 * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
3191 * is set) if the path is absolute.
3194 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
3198 char separator = '\0';
3202 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3203 "Invalid empty ", "pathname");
3204 return (ARCHIVE_FAILED);
3207 #if defined(__CYGWIN__)
3208 cleanup_pathname_win(path);
3210 /* Skip leading '/'. */
3212 if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
3213 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3214 "Path is ", "absolute");
3215 return (ARCHIVE_FAILED);
3221 /* Scan the pathname one element at a time. */
3223 /* src points to first char after '/' */
3224 if (src[0] == '\0') {
3226 } else if (src[0] == '/') {
3227 /* Found '//', ignore second one. */
3230 } else if (src[0] == '.') {
3231 if (src[1] == '\0') {
3232 /* Ignore trailing '.' */
3234 } else if (src[1] == '/') {
3238 } else if (src[1] == '.') {
3239 if (src[2] == '/' || src[2] == '\0') {
3240 /* Conditionally warn about '..' */
3242 & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3243 fsobj_error(a_eno, a_estr,
3245 "Path contains ", "'..'");
3246 return (ARCHIVE_FAILED);
3250 * Note: Under no circumstances do we
3251 * remove '..' elements. In
3252 * particular, restoring
3253 * '/foo/../bar/' should create the
3254 * 'foo' dir as a side-effect.
3259 /* Copy current element, including leading '/'. */
3262 while (*src != '\0' && *src != '/') {
3269 /* Skip '/' separator. */
3273 * We've just copied zero or more path elements, not including the
3278 * Nothing got copied. The path must have been something
3279 * like '.' or '/' or './' or '/././././/./'.
3286 /* Terminate the result. */
3288 return (ARCHIVE_OK);
3292 cleanup_pathname(struct archive_write_disk *a)
3294 struct archive_string error_string;
3297 archive_string_init(&error_string);
3298 rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3300 if (rc != ARCHIVE_OK) {
3301 archive_set_error(&a->archive, error_number, "%s",
3304 archive_string_free(&error_string);
3309 * Create the parent directory of the specified path, assuming path
3310 * is already in mutable storage.
3313 create_parent_dir(struct archive_write_disk *a, char *path)
3318 /* Remove tail element to obtain parent name. */
3319 slash = strrchr(path, '/');
3321 return (ARCHIVE_OK);
3323 r = create_dir(a, path);
3329 * Create the specified dir, recursing to create parents as necessary.
3331 * Returns ARCHIVE_OK if the path exists when we're done here.
3332 * Otherwise, returns ARCHIVE_FAILED.
3333 * Assumes path is in mutable storage; path is unchanged on exit.
3336 create_dir(struct archive_write_disk *a, char *path)
3339 struct fixup_entry *le;
3341 mode_t mode_final, mode;
3344 /* Check for special names and just skip them. */
3345 slash = strrchr(path, '/');
3351 if (base[0] == '\0' ||
3352 (base[0] == '.' && base[1] == '\0') ||
3353 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
3354 /* Don't bother trying to create null path, '.', or '..'. */
3355 if (slash != NULL) {
3357 r = create_dir(a, path);
3361 return (ARCHIVE_OK);
3365 * Yes, this should be stat() and not lstat(). Using lstat()
3366 * here loses the ability to extract through symlinks. Also note
3367 * that this should not use the a->st cache.
3369 if (la_stat(path, &st) == 0) {
3370 if (S_ISDIR(st.st_mode))
3371 return (ARCHIVE_OK);
3372 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
3373 archive_set_error(&a->archive, EEXIST,
3374 "Can't create directory '%s'", path);
3375 return (ARCHIVE_FAILED);
3377 if (unlink(path) != 0) {
3378 archive_set_error(&a->archive, errno,
3379 "Can't create directory '%s': "
3380 "Conflicting file cannot be removed",
3382 return (ARCHIVE_FAILED);
3384 } else if (errno != ENOENT && errno != ENOTDIR) {
3386 archive_set_error(&a->archive, errno,
3387 "Can't test directory '%s'", path);
3388 return (ARCHIVE_FAILED);
3389 } else if (slash != NULL) {
3391 r = create_dir(a, path);
3393 if (r != ARCHIVE_OK)
3398 * Mode we want for the final restored directory. Per POSIX,
3399 * implicitly-created dirs must be created obeying the umask.
3400 * There's no mention whether this is different for privileged
3401 * restores (which the rest of this code handles by pretending
3402 * umask=0). I've chosen here to always obey the user's umask for
3403 * implicit dirs, even if _EXTRACT_PERM was specified.
3405 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3406 /* Mode we want on disk during the restore process. */
3408 mode |= MINIMUM_DIR_MODE;
3409 mode &= MAXIMUM_DIR_MODE;
3410 if (mkdir(path, mode) == 0) {
3411 if (mode != mode_final) {
3412 le = new_fixup(a, path);
3414 return (ARCHIVE_FATAL);
3415 le->fixup |=TODO_MODE_BASE;
3416 le->mode = mode_final;
3418 return (ARCHIVE_OK);
3422 * Without the following check, a/b/../b/c/d fails at the
3423 * second visit to 'b', so 'd' can't be created. Note that we
3424 * don't add it to the fixup list here, as it's already been
3427 if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3428 return (ARCHIVE_OK);
3430 archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3432 return (ARCHIVE_FAILED);
3436 * Note: Although we can skip setting the user id if the desired user
3437 * id matches the current user, we cannot skip setting the group, as
3438 * many systems set the gid based on the containing directory. So
3439 * we have to perform a chown syscall if we want to set the SGID
3440 * bit. (The alternative is to stat() and then possibly chown(); it's
3441 * more efficient to skip the stat() and just always chown().) Note
3442 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3443 * allows set_mode to skip the stat() check for the GID.
3446 set_ownership(struct archive_write_disk *a)
3448 #if !defined(__CYGWIN__) && !defined(__linux__)
3450 * On Linux, a process may have the CAP_CHOWN capability.
3451 * On Windows there is no 'root' user with uid 0.
3452 * Elsewhere we can skip calling chown if we are not root and the desired
3453 * user id does not match the current user.
3455 if (a->user_uid != 0 && a->user_uid != a->uid) {
3456 archive_set_error(&a->archive, errno,
3457 "Can't set UID=%jd", (intmax_t)a->uid);
3458 return (ARCHIVE_WARN);
3463 /* If we have an fd, we can avoid a race. */
3464 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3465 /* We've set owner and know uid/gid are correct. */
3466 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3467 return (ARCHIVE_OK);
3471 /* We prefer lchown() but will use chown() if that's all we have. */
3472 /* Of course, if we have neither, this will always fail. */
3474 if (lchown(a->name, a->uid, a->gid) == 0) {
3475 /* We've set owner and know uid/gid are correct. */
3476 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3477 return (ARCHIVE_OK);
3480 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3481 /* We've set owner and know uid/gid are correct. */
3482 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3483 return (ARCHIVE_OK);
3487 archive_set_error(&a->archive, errno,
3488 "Can't set user=%jd/group=%jd for %s",
3489 (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3490 return (ARCHIVE_WARN);
3494 * Note: Returns 0 on success, non-zero on failure.
3497 set_time(int fd, int mode, const char *name,
3498 time_t atime, long atime_nsec,
3499 time_t mtime, long mtime_nsec)
3501 /* Select the best implementation for this platform. */
3502 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3504 * utimensat() and futimens() are defined in
3505 * POSIX.1-2008. They support ns resolution and setting times
3506 * on fds and symlinks.
3508 struct timespec ts[2];
3509 (void)mode; /* UNUSED */
3510 ts[0].tv_sec = atime;
3511 ts[0].tv_nsec = atime_nsec;
3512 ts[1].tv_sec = mtime;
3513 ts[1].tv_nsec = mtime_nsec;
3515 return futimens(fd, ts);
3516 return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3520 * The utimes()-family functions support µs-resolution and
3521 * setting times fds and symlinks. utimes() is documented as
3522 * LEGACY by POSIX, futimes() and lutimes() are not described
3525 struct timeval times[2];
3527 times[0].tv_sec = atime;
3528 times[0].tv_usec = atime_nsec / 1000;
3529 times[1].tv_sec = mtime;
3530 times[1].tv_usec = mtime_nsec / 1000;
3534 return (futimes(fd, times));
3536 (void)fd; /* UNUSED */
3539 (void)mode; /* UNUSED */
3540 return (lutimes(name, times));
3544 return (utimes(name, times));
3547 #elif defined(HAVE_UTIME)
3549 * utime() is POSIX-standard but only supports 1s resolution and
3550 * does not support fds or symlinks.
3552 struct utimbuf times;
3553 (void)fd; /* UNUSED */
3554 (void)name; /* UNUSED */
3555 (void)atime_nsec; /* UNUSED */
3556 (void)mtime_nsec; /* UNUSED */
3557 times.actime = atime;
3558 times.modtime = mtime;
3560 return (ARCHIVE_OK);
3561 return (utime(name, ×));
3565 * We don't know how to set the time on this platform.
3567 (void)fd; /* UNUSED */
3568 (void)mode; /* UNUSED */
3569 (void)name; /* UNUSED */
3570 (void)atime_nsec; /* UNUSED */
3571 (void)mtime_nsec; /* UNUSED */
3572 return (ARCHIVE_WARN);
3578 set_time_tru64(int fd, int mode, const char *name,
3579 time_t atime, long atime_nsec,
3580 time_t mtime, long mtime_nsec,
3581 time_t ctime, long ctime_nsec)
3583 struct attr_timbuf tstamp;
3584 tstamp.atime.tv_sec = atime;
3585 tstamp.mtime.tv_sec = mtime;
3586 tstamp.ctime.tv_sec = ctime;
3587 #if defined (__hpux) && defined (__ia64)
3588 tstamp.atime.tv_nsec = atime_nsec;
3589 tstamp.mtime.tv_nsec = mtime_nsec;
3590 tstamp.ctime.tv_nsec = ctime_nsec;
3592 tstamp.atime.tv_usec = atime_nsec / 1000;
3593 tstamp.mtime.tv_usec = mtime_nsec / 1000;
3594 tstamp.ctime.tv_usec = ctime_nsec / 1000;
3596 return (fcntl(fd,F_SETTIMES,&tstamp));
3598 #endif /* F_SETTIMES */
3601 set_times(struct archive_write_disk *a,
3602 int fd, int mode, const char *name,
3603 time_t atime, long atime_nanos,
3604 time_t birthtime, long birthtime_nanos,
3605 time_t mtime, long mtime_nanos,
3606 time_t cctime, long ctime_nanos)
3608 /* Note: set_time doesn't use libarchive return conventions!
3609 * It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */
3614 * on Tru64 try own fcntl first which can restore even the
3615 * ctime, fall back to default code path below if it fails
3616 * or if we are not running as root
3618 if (a->user_uid == 0 &&
3619 set_time_tru64(fd, mode, name,
3620 atime, atime_nanos, mtime,
3621 mtime_nanos, cctime, ctime_nanos) == 0) {
3622 return (ARCHIVE_OK);
3625 (void)cctime; /* UNUSED */
3626 (void)ctime_nanos; /* UNUSED */
3629 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3631 * If you have struct stat.st_birthtime, we assume BSD
3632 * birthtime semantics, in which {f,l,}utimes() updates
3633 * birthtime to earliest mtime. So we set the time twice,
3634 * first using the birthtime, then using the mtime. If
3635 * birthtime == mtime, this isn't necessary, so we skip it.
3636 * If birthtime > mtime, then this won't work, so we skip it.
3638 if (birthtime < mtime
3639 || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3640 r1 = set_time(fd, mode, name,
3642 birthtime, birthtime_nanos);
3644 (void)birthtime; /* UNUSED */
3645 (void)birthtime_nanos; /* UNUSED */
3647 r2 = set_time(fd, mode, name,
3649 mtime, mtime_nanos);
3650 if (r1 != 0 || r2 != 0) {
3651 archive_set_error(&a->archive, errno,
3652 "Can't restore time");
3653 return (ARCHIVE_WARN);
3655 return (ARCHIVE_OK);
3659 set_times_from_entry(struct archive_write_disk *a)
3661 time_t atime, birthtime, mtime, cctime;
3662 long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3664 /* Suitable defaults. */
3665 atime = birthtime = mtime = cctime = a->start_time;
3666 atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3668 /* If no time was provided, we're done. */
3669 if (!archive_entry_atime_is_set(a->entry)
3670 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
3671 && !archive_entry_birthtime_is_set(a->entry)
3673 && !archive_entry_mtime_is_set(a->entry))
3674 return (ARCHIVE_OK);
3676 if (archive_entry_atime_is_set(a->entry)) {
3677 atime = archive_entry_atime(a->entry);
3678 atime_nsec = archive_entry_atime_nsec(a->entry);
3680 if (archive_entry_birthtime_is_set(a->entry)) {
3681 birthtime = archive_entry_birthtime(a->entry);
3682 birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3684 if (archive_entry_mtime_is_set(a->entry)) {
3685 mtime = archive_entry_mtime(a->entry);
3686 mtime_nsec = archive_entry_mtime_nsec(a->entry);
3688 if (archive_entry_ctime_is_set(a->entry)) {
3689 cctime = archive_entry_ctime(a->entry);
3690 ctime_nsec = archive_entry_ctime_nsec(a->entry);
3693 return set_times(a, a->fd, a->mode, a->name,
3695 birthtime, birthtime_nsec,
3697 cctime, ctime_nsec);
3701 set_mode(struct archive_write_disk *a, int mode)
3705 mode &= 07777; /* Strip off file type bits. */
3707 if (a->todo & TODO_SGID_CHECK) {
3709 * If we don't know the GID is right, we must stat()
3710 * to verify it. We can't just check the GID of this
3711 * process, since systems sometimes set GID from
3712 * the enclosing dir or based on ACLs.
3714 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3716 if (a->pst->st_gid != a->gid) {
3718 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3720 * This is only an error if you
3721 * requested owner restore. If you
3722 * didn't, we'll try to restore
3723 * sgid/suid, but won't consider it a
3724 * problem if we can't.
3726 archive_set_error(&a->archive, -1,
3727 "Can't restore SGID bit");
3731 /* While we're here, double-check the UID. */
3732 if (a->pst->st_uid != a->uid
3733 && (a->todo & TODO_SUID)) {
3735 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3736 archive_set_error(&a->archive, -1,
3737 "Can't restore SUID bit");
3741 a->todo &= ~TODO_SGID_CHECK;
3742 a->todo &= ~TODO_SUID_CHECK;
3743 } else if (a->todo & TODO_SUID_CHECK) {
3745 * If we don't know the UID is right, we can just check
3746 * the user, since all systems set the file UID from
3749 if (a->user_uid != a->uid) {
3751 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3752 archive_set_error(&a->archive, -1,
3753 "Can't make file SUID");
3757 a->todo &= ~TODO_SUID_CHECK;
3760 if (S_ISLNK(a->mode)) {
3763 * If this is a symlink, use lchmod(). If the
3764 * platform doesn't support lchmod(), just skip it. A
3765 * platform that doesn't provide a way to set
3766 * permissions on symlinks probably ignores
3767 * permissions on symlinks, so a failure here has no
3770 if (lchmod(a->name, mode) != 0) {
3774 #if ENOTSUP != EOPNOTSUPP
3778 * if lchmod is defined but the platform
3779 * doesn't support it, silently ignore
3784 archive_set_error(&a->archive, errno,
3785 "Can't set permissions to 0%o", (int)mode);
3790 } else if (!S_ISDIR(a->mode)) {
3792 * If it's not a symlink and not a dir, then use
3793 * fchmod() or chmod(), depending on whether we have
3794 * an fd. Dirs get their perms set during the
3795 * post-extract fixup, which is handled elsewhere.
3799 r2 = fchmod(a->fd, mode);
3802 /* If this platform lacks fchmod(), then
3803 * we'll just use chmod(). */
3804 r2 = chmod(a->name, mode);
3807 archive_set_error(&a->archive, errno,
3808 "Can't set permissions to 0%o", (int)mode);
3816 set_fflags(struct archive_write_disk *a)
3818 struct fixup_entry *le;
3819 unsigned long set, clear;
3821 mode_t mode = archive_entry_mode(a->entry);
3823 * Make 'critical_flags' hold all file flags that can't be
3824 * immediately restored. For example, on BSD systems,
3825 * SF_IMMUTABLE prevents hardlinks from being created, so
3826 * should not be set until after any hardlinks are created. To
3827 * preserve some semblance of portability, this uses #ifdef
3828 * extensively. Ugly, but it works.
3830 * Yes, Virginia, this does create a security race. It's mitigated
3831 * somewhat by the practice of creating dirs 0700 until the extract
3832 * is done, but it would be nice if we could do more than that.
3833 * People restoring critical file systems should be wary of
3834 * other programs that might try to muck with files as they're
3837 const int critical_flags = 0
3850 #if defined(FS_APPEND_FL)
3852 #elif defined(EXT2_APPEND_FL)
3855 #if defined(FS_IMMUTABLE_FL)
3857 #elif defined(EXT2_IMMUTABLE_FL)
3860 #ifdef FS_JOURNAL_DATA_FL
3861 | FS_JOURNAL_DATA_FL
3865 if (a->todo & TODO_FFLAGS) {
3866 archive_entry_fflags(a->entry, &set, &clear);
3869 * The first test encourages the compiler to eliminate
3870 * all of this if it's not necessary.
3872 if ((critical_flags != 0) && (set & critical_flags)) {
3873 le = current_fixup(a, a->name);
3875 return (ARCHIVE_FATAL);
3876 le->filetype = archive_entry_filetype(a->entry);
3877 le->fixup |= TODO_FFLAGS;
3878 le->fflags_set = set;
3879 /* Store the mode if it's not already there. */
3880 if ((le->fixup & TODO_MODE) == 0)
3883 r = set_fflags_platform(a, a->fd,
3884 a->name, mode, set, clear);
3885 if (r != ARCHIVE_OK)
3889 return (ARCHIVE_OK);
3893 clear_nochange_fflags(struct archive_write_disk *a)
3895 mode_t mode = archive_entry_mode(a->entry);
3896 const int nochange_flags = 0
3909 #ifdef EXT2_APPEND_FL
3912 #ifdef EXT2_IMMUTABLE_FL
3917 return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3922 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3924 * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3927 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3928 mode_t mode, unsigned long set, unsigned long clear)
3931 const int sf_mask = 0
3945 (void)mode; /* UNUSED */
3947 if (set == 0 && clear == 0)
3948 return (ARCHIVE_OK);
3951 * XXX Is the stat here really necessary? Or can I just use
3952 * the 'set' flags directly? In particular, I'm not sure
3953 * about the correct approach if we're overwriting an existing
3954 * file that already has flags on it. XXX
3956 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3959 a->st.st_flags &= ~clear;
3960 a->st.st_flags |= set;
3962 /* Only super-user may change SF_* flags */
3964 if (a->user_uid != 0)
3965 a->st.st_flags &= ~sf_mask;
3967 #ifdef HAVE_FCHFLAGS
3968 /* If platform has fchflags() and we were given an fd, use it. */
3969 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
3970 return (ARCHIVE_OK);
3973 * If we can't use the fd to set the flags, we'll use the
3974 * pathname to set flags. We prefer lchflags() but will use
3975 * chflags() if we must.
3977 #ifdef HAVE_LCHFLAGS
3978 if (lchflags(name, a->st.st_flags) == 0)
3979 return (ARCHIVE_OK);
3980 #elif defined(HAVE_CHFLAGS)
3981 if (S_ISLNK(a->st.st_mode)) {
3982 archive_set_error(&a->archive, errno,
3983 "Can't set file flags on symlink.");
3984 return (ARCHIVE_WARN);
3986 if (chflags(name, a->st.st_flags) == 0)
3987 return (ARCHIVE_OK);
3989 archive_set_error(&a->archive, errno,
3990 "Failed to set file flags");
3991 return (ARCHIVE_WARN);
3994 #elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \
3995 defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
3996 (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \
3997 defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
3999 * Linux uses ioctl() to read and write file flags.
4002 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4003 mode_t mode, unsigned long set, unsigned long clear)
4007 int newflags, oldflags;
4009 * Linux has no define for the flags that are only settable by
4010 * the root user. This code may seem a little complex, but
4011 * there seem to be some Linux systems that lack these
4012 * defines. (?) The code below degrades reasonably gracefully
4013 * if sf_mask is incomplete.
4015 const int sf_mask = 0
4016 #if defined(FS_IMMUTABLE_FL)
4018 #elif defined(EXT2_IMMUTABLE_FL)
4021 #if defined(FS_APPEND_FL)
4023 #elif defined(EXT2_APPEND_FL)
4026 #if defined(FS_JOURNAL_DATA_FL)
4027 | FS_JOURNAL_DATA_FL
4031 if (set == 0 && clear == 0)
4032 return (ARCHIVE_OK);
4033 /* Only regular files and dirs can have flags. */
4034 if (!S_ISREG(mode) && !S_ISDIR(mode))
4035 return (ARCHIVE_OK);
4037 /* If we weren't given an fd, open it ourselves. */
4039 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY |
4040 O_CLOEXEC | O_NOFOLLOW);
4041 __archive_ensure_cloexec_flag(myfd);
4044 return (ARCHIVE_OK);
4047 * XXX As above, this would be way simpler if we didn't have
4048 * to read the current flags from disk. XXX
4052 /* Read the current file flags. */
4054 #ifdef FS_IOC_GETFLAGS
4062 /* Try setting the flags as given. */
4063 newflags = (oldflags & ~clear) | set;
4065 #ifdef FS_IOC_SETFLAGS
4075 /* If we couldn't set all the flags, try again with a subset. */
4076 newflags &= ~sf_mask;
4077 oldflags &= sf_mask;
4078 newflags |= oldflags;
4080 #ifdef FS_IOC_SETFLAGS
4088 /* We couldn't set the flags, so report the failure. */
4090 archive_set_error(&a->archive, errno,
4091 "Failed to set file flags");
4102 * Of course, some systems have neither BSD chflags() nor Linux' flags
4103 * support through ioctl().
4106 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4107 mode_t mode, unsigned long set, unsigned long clear)
4109 (void)a; /* UNUSED */
4110 (void)fd; /* UNUSED */
4111 (void)name; /* UNUSED */
4112 (void)mode; /* UNUSED */
4113 (void)set; /* UNUSED */
4114 (void)clear; /* UNUSED */
4115 return (ARCHIVE_OK);
4118 #endif /* __linux */
4120 #ifndef HAVE_COPYFILE_H
4121 /* Default is to simply drop Mac extended metadata. */
4123 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4124 const void *metadata, size_t metadata_size)
4126 (void)a; /* UNUSED */
4127 (void)pathname; /* UNUSED */
4128 (void)metadata; /* UNUSED */
4129 (void)metadata_size; /* UNUSED */
4130 return (ARCHIVE_OK);
4134 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4136 (void)a; /* UNUSED */
4137 (void)pathname; /* UNUSED */
4138 return (ARCHIVE_OK);
4143 * On Mac OS, we use copyfile() to unpack the metadata and
4144 * apply it to the target file.
4147 #if defined(HAVE_SYS_XATTR_H)
4149 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
4152 char *xattr_names = NULL, *xattr_val = NULL;
4153 int ret = ARCHIVE_OK, xattr_i;
4155 xattr_size = flistxattr(tmpfd, NULL, 0, 0);
4156 if (xattr_size == -1) {
4157 archive_set_error(&a->archive, errno,
4158 "Failed to read metadata(xattr)");
4162 xattr_names = malloc(xattr_size);
4163 if (xattr_names == NULL) {
4164 archive_set_error(&a->archive, ENOMEM,
4165 "Can't allocate memory for metadata(xattr)");
4166 ret = ARCHIVE_FATAL;
4169 xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
4170 if (xattr_size == -1) {
4171 archive_set_error(&a->archive, errno,
4172 "Failed to read metadata(xattr)");
4176 for (xattr_i = 0; xattr_i < xattr_size;
4177 xattr_i += strlen(xattr_names + xattr_i) + 1) {
4178 char *xattr_val_saved;
4182 s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
4184 archive_set_error(&a->archive, errno,
4185 "Failed to get metadata(xattr)");
4189 xattr_val_saved = xattr_val;
4190 xattr_val = realloc(xattr_val, s);
4191 if (xattr_val == NULL) {
4192 archive_set_error(&a->archive, ENOMEM,
4193 "Failed to get metadata(xattr)");
4195 free(xattr_val_saved);
4198 s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4200 archive_set_error(&a->archive, errno,
4201 "Failed to get metadata(xattr)");
4205 f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4207 archive_set_error(&a->archive, errno,
4208 "Failed to get metadata(xattr)");
4221 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
4223 #ifndef HAVE_SYS_ACL_H
4226 acl_t acl, dfacl = NULL;
4227 int acl_r, ret = ARCHIVE_OK;
4229 acl = acl_get_fd(tmpfd);
4231 if (errno == ENOENT)
4232 /* There are not any ACLs. */
4234 archive_set_error(&a->archive, errno,
4235 "Failed to get metadata(acl)");
4239 dfacl = acl_dup(acl);
4240 acl_r = acl_set_fd(dffd, dfacl);
4242 archive_set_error(&a->archive, errno,
4243 "Failed to get metadata(acl)");
4257 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4259 struct archive_string tmpdatafork;
4262 archive_string_init(&tmpdatafork);
4263 archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
4264 tmpfd = mkstemp(tmpdatafork.s);
4266 archive_set_error(&a->archive, errno,
4267 "Failed to mkstemp");
4268 archive_string_free(&tmpdatafork);
4271 if (copyfile(pathname, tmpdatafork.s, 0,
4272 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4273 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4274 archive_set_error(&a->archive, errno,
4275 "Failed to restore metadata");
4279 unlink(tmpdatafork.s);
4280 archive_string_free(&tmpdatafork);
4285 copy_metadata(struct archive_write_disk *a, const char *metadata,
4286 const char *datafork, int datafork_compressed)
4288 int ret = ARCHIVE_OK;
4290 if (datafork_compressed) {
4293 tmpfd = create_tempdatafork(a, metadata);
4295 return (ARCHIVE_WARN);
4298 * Do not open the data fork compressed by HFS+ compression
4299 * with at least a writing mode(O_RDWR or O_WRONLY). it
4300 * makes the data fork uncompressed.
4302 dffd = open(datafork, 0);
4304 archive_set_error(&a->archive, errno,
4305 "Failed to open the data fork for metadata");
4307 return (ARCHIVE_WARN);
4310 #if defined(HAVE_SYS_XATTR_H)
4311 ret = copy_xattrs(a, tmpfd, dffd);
4312 if (ret == ARCHIVE_OK)
4314 ret = copy_acls(a, tmpfd, dffd);
4318 if (copyfile(metadata, datafork, 0,
4319 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4320 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4321 archive_set_error(&a->archive, errno,
4322 "Failed to restore metadata");
4330 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4331 const void *metadata, size_t metadata_size)
4333 struct archive_string tmp;
4336 int ret = ARCHIVE_OK;
4338 /* This would be simpler if copyfile() could just accept the
4339 * metadata as a block of memory; then we could sidestep this
4340 * silly dance of writing the data to disk just so that
4341 * copyfile() can read it back in again. */
4342 archive_string_init(&tmp);
4343 archive_strcpy(&tmp, pathname);
4344 archive_strcat(&tmp, ".XXXXXX");
4345 fd = mkstemp(tmp.s);
4348 archive_set_error(&a->archive, errno,
4349 "Failed to restore metadata");
4350 archive_string_free(&tmp);
4351 return (ARCHIVE_WARN);
4353 written = write(fd, metadata, metadata_size);
4355 if ((size_t)written != metadata_size) {
4356 archive_set_error(&a->archive, errno,
4357 "Failed to restore metadata");
4362 #if defined(UF_COMPRESSED)
4363 if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
4364 (ret = lazy_stat(a)) == ARCHIVE_OK)
4365 compressed = a->st.st_flags & UF_COMPRESSED;
4369 ret = copy_metadata(a, tmp.s, pathname, compressed);
4372 archive_string_free(&tmp);
4377 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4382 struct archive_string datafork;
4383 int fd = -1, ret = ARCHIVE_OK;
4385 archive_string_init(&datafork);
4386 /* Check if the current file name is a type of the resource
4388 p = strrchr(pathname, '/');
4393 if (p[0] != '.' || p[1] != '_')
4394 goto skip_appledouble;
4397 * Check if the data fork file exists.
4399 * TODO: Check if this write disk object has handled it.
4401 archive_strncpy(&datafork, pathname, p - pathname);
4402 archive_strcat(&datafork, p + 2);
4403 if (lstat(datafork.s, &st) == -1 ||
4404 (st.st_mode & AE_IFMT) != AE_IFREG)
4405 goto skip_appledouble;
4408 * Check if the file is in the AppleDouble form.
4410 fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4411 __archive_ensure_cloexec_flag(fd);
4413 archive_set_error(&a->archive, errno,
4414 "Failed to open a restoring file");
4416 goto skip_appledouble;
4418 if (read(fd, buff, 8) == -1) {
4419 archive_set_error(&a->archive, errno,
4420 "Failed to read a restoring file");
4423 goto skip_appledouble;
4426 /* Check AppleDouble Magic Code. */
4427 if (archive_be32dec(buff) != 0x00051607)
4428 goto skip_appledouble;
4429 /* Check AppleDouble Version. */
4430 if (archive_be32dec(buff+4) != 0x00020000)
4431 goto skip_appledouble;
4433 ret = copy_metadata(a, pathname, datafork.s,
4434 #if defined(UF_COMPRESSED)
4435 st.st_flags & UF_COMPRESSED);
4439 if (ret == ARCHIVE_OK) {
4444 archive_string_free(&datafork);
4449 #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4451 * Restore extended attributes - Linux, Darwin and AIX implementations:
4452 * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4455 set_xattrs(struct archive_write_disk *a)
4457 struct archive_entry *entry = a->entry;
4458 struct archive_string errlist;
4459 int ret = ARCHIVE_OK;
4460 int i = archive_entry_xattr_reset(entry);
4463 archive_string_init(&errlist);
4471 archive_entry_xattr_next(entry, &name, &value, &size);
4475 #if ARCHIVE_XATTR_LINUX
4476 /* Linux: quietly skip POSIX.1e ACL extended attributes */
4477 if (strncmp(name, "system.", 7) == 0 &&
4478 (strcmp(name + 7, "posix_acl_access") == 0 ||
4479 strcmp(name + 7, "posix_acl_default") == 0))
4481 if (strncmp(name, "trusted.SGI_", 12) == 0 &&
4482 (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
4483 strcmp(name + 12, "ACL_FILE") == 0))
4486 /* Linux: xfsroot namespace is obsolete and unsupported */
4487 if (strncmp(name, "xfsroot.", 8) == 0) {
4489 archive_strcat(&errlist, name);
4490 archive_strappend_char(&errlist, ' ');
4496 #if ARCHIVE_XATTR_LINUX
4497 e = fsetxattr(a->fd, name, value, size, 0);
4498 #elif ARCHIVE_XATTR_DARWIN
4499 e = fsetxattr(a->fd, name, value, size, 0, 0);
4500 #elif ARCHIVE_XATTR_AIX
4501 e = fsetea(a->fd, name, value, size, 0);
4504 #if ARCHIVE_XATTR_LINUX
4505 e = lsetxattr(archive_entry_pathname(entry),
4506 name, value, size, 0);
4507 #elif ARCHIVE_XATTR_DARWIN
4508 e = setxattr(archive_entry_pathname(entry),
4509 name, value, size, 0, XATTR_NOFOLLOW);
4510 #elif ARCHIVE_XATTR_AIX
4511 e = lsetea(archive_entry_pathname(entry),
4512 name, value, size, 0);
4517 archive_strcat(&errlist, name);
4518 archive_strappend_char(&errlist, ' ');
4519 if (errno != ENOTSUP && errno != ENOSYS)
4524 if (ret == ARCHIVE_WARN) {
4525 if (fail && errlist.length > 0) {
4527 errlist.s[errlist.length] = '\0';
4528 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4529 "Cannot restore extended attributes: %s",
4532 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4533 "Cannot restore extended "
4534 "attributes on this file system.");
4537 archive_string_free(&errlist);
4540 #elif ARCHIVE_XATTR_FREEBSD
4542 * Restore extended attributes - FreeBSD implementation
4545 set_xattrs(struct archive_write_disk *a)
4547 struct archive_entry *entry = a->entry;
4548 struct archive_string errlist;
4549 int ret = ARCHIVE_OK;
4550 int i = archive_entry_xattr_reset(entry);
4553 archive_string_init(&errlist);
4559 archive_entry_xattr_next(entry, &name, &value, &size);
4564 namespace = EXTATTR_NAMESPACE_USER;
4566 if (strncmp(name, "user.", 5) == 0) {
4567 /* "user." attributes go to user namespace */
4569 namespace = EXTATTR_NAMESPACE_USER;
4570 } else if (strncmp(name, "system.", 7) == 0) {
4572 namespace = EXTATTR_NAMESPACE_SYSTEM;
4573 if (!strcmp(name, "nfs4.acl") ||
4574 !strcmp(name, "posix1e.acl_access") ||
4575 !strcmp(name, "posix1e.acl_default"))
4578 /* Other namespaces are unsupported */
4579 archive_strcat(&errlist, name);
4580 archive_strappend_char(&errlist, ' ');
4588 * On FreeBSD, extattr_set_fd does not
4589 * return the same as
4590 * extattr_set_file. It returns zero
4591 * on success, non-zero on failure.
4593 * We can detect the failure by
4594 * manually setting errno prior to the
4595 * call and checking after.
4597 * If errno remains zero, fake the
4598 * return value by setting e to size.
4600 * This is a hack for now until I
4601 * (Shawn Webb) get FreeBSD to fix the
4602 * issue, if that's even possible.
4605 e = extattr_set_fd(a->fd, namespace, name,
4607 if (e == 0 && errno == 0) {
4611 e = extattr_set_link(
4612 archive_entry_pathname(entry), namespace,
4615 if (e != (int)size) {
4616 archive_strcat(&errlist, name);
4617 archive_strappend_char(&errlist, ' ');
4619 if (errno != ENOTSUP && errno != ENOSYS)
4625 if (ret == ARCHIVE_WARN) {
4626 if (fail && errlist.length > 0) {
4628 errlist.s[errlist.length] = '\0';
4630 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4631 "Cannot restore extended attributes: %s",
4634 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4635 "Cannot restore extended "
4636 "attributes on this file system.");
4639 archive_string_free(&errlist);
4644 * Restore extended attributes - stub implementation for unsupported systems
4647 set_xattrs(struct archive_write_disk *a)
4649 static int warning_done = 0;
4651 /* If there aren't any extended attributes, then it's okay not
4652 * to extract them, otherwise, issue a single warning. */
4653 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4655 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4656 "Cannot restore extended attributes on this system");
4657 return (ARCHIVE_WARN);
4659 /* Warning was already emitted; suppress further warnings. */
4660 return (ARCHIVE_OK);
4665 * Test if file on disk is older than entry.
4668 older(struct stat *st, struct archive_entry *entry)
4670 /* First, test the seconds and return if we have a definite answer. */
4671 /* Definitely older. */
4672 if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry)))
4674 /* Definitely younger. */
4675 if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4677 /* If this platform supports fractional seconds, try those. */
4678 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4679 /* Definitely older. */
4680 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4682 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4683 /* Definitely older. */
4684 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4686 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4688 if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4690 #elif HAVE_STRUCT_STAT_ST_UMTIME
4692 if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4694 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4696 if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4699 /* This system doesn't have high-res timestamps. */
4701 /* Same age or newer, so not older. */
4705 #ifndef ARCHIVE_ACL_SUPPORT
4707 archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4708 struct archive_acl *abstract_acl, __LA_MODE_T mode)
4710 (void)a; /* UNUSED */
4711 (void)fd; /* UNUSED */
4712 (void)name; /* UNUSED */
4713 (void)abstract_acl; /* UNUSED */
4714 (void)mode; /* UNUSED */
4715 return (ARCHIVE_OK);
4719 #endif /* !_WIN32 || __CYGWIN__ */