1 /*-
2  * Copyright (c) 2003-2010 Tim Kientzle
3  * Copyright (c) 2012 Michihiro NAKAJIMA
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
15  *
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.
26  */
27 
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD$");
30 
31 #if !defined(_WIN32) || defined(__CYGWIN__)
32 
33 #ifdef HAVE_SYS_TYPES_H
34 #include <sys/types.h>
35 #endif
36 #ifdef HAVE_SYS_ACL_H
37 #include <sys/acl.h>
38 #endif
39 #ifdef HAVE_SYS_EXTATTR_H
40 #include <sys/extattr.h>
41 #endif
42 #if HAVE_SYS_XATTR_H
43 #include <sys/xattr.h>
44 #elif HAVE_ATTR_XATTR_H
45 #include <attr/xattr.h>
46 #endif
47 #ifdef HAVE_SYS_EA_H
48 #include <sys/ea.h>
49 #endif
50 #ifdef HAVE_SYS_IOCTL_H
51 #include <sys/ioctl.h>
52 #endif
53 #ifdef HAVE_SYS_STAT_H
54 #include <sys/stat.h>
55 #endif
56 #ifdef HAVE_SYS_TIME_H
57 #include <sys/time.h>
58 #endif
59 #ifdef HAVE_SYS_UTIME_H
60 #include <sys/utime.h>
61 #endif
62 #ifdef HAVE_COPYFILE_H
63 #include <copyfile.h>
64 #endif
65 #ifdef HAVE_ERRNO_H
66 #include <errno.h>
67 #endif
68 #ifdef HAVE_FCNTL_H
69 #include <fcntl.h>
70 #endif
71 #ifdef HAVE_GRP_H
72 #include <grp.h>
73 #endif
74 #ifdef HAVE_LANGINFO_H
75 #include <langinfo.h>
76 #endif
77 #ifdef HAVE_LINUX_FS_H
78 #include <linux/fs.h>	/* for Linux file flags */
79 #endif
80 /*
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.
83  */
84 #ifdef HAVE_LINUX_EXT2_FS_H
85 #include <linux/ext2_fs.h>	/* for Linux file flags */
86 #endif
87 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
88 #include <ext2fs/ext2_fs.h>	/* Linux file flags, broken on Cygwin */
89 #endif
90 #ifdef HAVE_LIMITS_H
91 #include <limits.h>
92 #endif
93 #ifdef HAVE_PWD_H
94 #include <pwd.h>
95 #endif
96 #include <stdio.h>
97 #ifdef HAVE_STDLIB_H
98 #include <stdlib.h>
99 #endif
100 #ifdef HAVE_STRING_H
101 #include <string.h>
102 #endif
103 #ifdef HAVE_UNISTD_H
104 #include <unistd.h>
105 #endif
106 #ifdef HAVE_UTIME_H
107 #include <utime.h>
108 #endif
109 #ifdef F_GETTIMES /* Tru64 specific */
110 #include <sys/fcntl1.h>
111 #endif
112 
113 /*
114  * Macro to cast st_mtime and time_t to an int64 so that 2 numbers can reliably be compared.
115  *
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
120  * to INT64_MAX.*
121  */
122 #define to_int64_time(t) \
123    ((t) < 0 ? (int64_t)(t) : (uint64_t)(t) > (uint64_t)INT64_MAX ? INT64_MAX : (int64_t)(t))
124 
125 #if __APPLE__
126 #include <TargetConditionals.h>
127 #if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
128 #include <quarantine.h>
129 #define HAVE_QUARANTINE 1
130 #endif
131 #endif
132 
133 #ifdef HAVE_ZLIB_H
134 #include <zlib.h>
135 #endif
136 
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. */
142 
143 #include "archive.h"
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"
150 
151 #ifndef O_BINARY
152 #define O_BINARY 0
153 #endif
154 #ifndef O_CLOEXEC
155 #define O_CLOEXEC 0
156 #endif
157 
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)
161 #undef O_NOFOLLOW
162 #endif
163 
164 #ifndef O_NOFOLLOW
165 #define O_NOFOLLOW 0
166 #endif
167 
168 #ifndef AT_FDCWD
169 #define AT_FDCWD -100
170 #endif
171 
172 struct fixup_entry {
173 	struct fixup_entry	*next;
174 	struct archive_acl	 acl;
175 	mode_t			 mode;
176 	__LA_MODE_T		 filetype;
177 	int64_t			 atime;
178 	int64_t                  birthtime;
179 	int64_t			 mtime;
180 	int64_t			 ctime;
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;
187 	void			*mac_metadata;
188 	int			 fixup; /* bitmask of what needs fixing */
189 	char			*name;
190 };
191 
192 /*
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.
204  */
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
220 
221 struct archive_write_disk {
222 	struct archive	archive;
223 
224 	mode_t			 user_umask;
225 	struct fixup_entry	*fixup_list;
226 	struct fixup_entry	*current_fixup;
227 	int64_t			 user_uid;
228 	int			 skip_file_set;
229 	int64_t			 skip_file_dev;
230 	int64_t			 skip_file_ino;
231 	time_t			 start_time;
232 
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;
239 
240 	/*
241 	 * Full path of last file to satisfy symlink checks.
242 	 */
243 	struct archive_string	path_safe;
244 
245 	/*
246 	 * Cached stat data from disk for the current entry.
247 	 * If this is valid, pst points to st.  Otherwise,
248 	 * pst is null.
249 	 */
250 	struct stat		 st;
251 	struct stat		*pst;
252 
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. */
260 	int			 todo;
261 	/* Tasks deferred until end-of-archive. */
262 	int			 deferred;
263 	/* Options requested by the client. */
264 	int			 flags;
265 	/* Handle for the file we're restoring. */
266 	int			 fd;
267 	/* Current offset for writing data to the file. */
268 	int64_t			 offset;
269 	/* Last offset actually written to disk. */
270 	int64_t			 fd_offset;
271 	/* Total bytes actually written to files. */
272 	int64_t			 total_bytes_written;
273 	/* Maximum size of file, -1 if unknown. */
274 	int64_t			 filesize;
275 	/* Dir we were in before this restore; only for deep paths. */
276 	int			 restore_pwd;
277 	/* Mode we should use for this entry; affected by _PERM and umask. */
278 	mode_t			 mode;
279 	/* UID/GID to use in restoring this entry. */
280 	int64_t			 uid;
281 	int64_t			 gid;
282 	/*
283 	 * HFS+ Compression.
284 	 */
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
300 	 * be placed. */
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;
307 #ifdef HAVE_ZLIB_H
308 	z_stream		 stream;
309 	int			 stream_valid;
310 	int			 decmpfs_compression_level;
311 #endif
312 };
313 
314 /*
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."
318  */
319 #define	DEFAULT_DIR_MODE 0777
320 /*
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
324  * applied.
325  */
326 #define	MINIMUM_DIR_MODE 0700
327 #define	MAXIMUM_DIR_MODE 0775
328 
329 /*
330  * Maximum uncompressed size of a decmpfs block.
331  */
332 #define MAX_DECMPFS_BLOCK_SIZE	(64 * 1024)
333 /*
334  * HFS+ compression type.
335  */
336 #define CMP_XATTR		3/* Compressed data in xattr. */
337 #define CMP_RESOURCE_FORK	4/* Compressed data in resource fork. */
338 /*
339  * HFS+ compression resource fork.
340  */
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"
349 #endif
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
355 
356 #define HFS_BLOCKS(s)	((s) >> 12)
357 
358 
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 *,
363 		    const char *);
364 static int	check_symlinks_fsobj(char *, int *, struct archive_string *,
365 		    int, int);
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);
372 #endif
373 static int	cleanup_pathname_fsobj(char *, int *, struct archive_string *,
374 		    int);
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);
400 
401 static struct archive_vtable *archive_write_disk_vtable(void);
402 
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 *,
410 		    size_t);
411 static ssize_t	_archive_write_disk_data_block(struct archive *, const void *,
412 		    size_t, int64_t);
413 
414 static int
415 la_mktemp(struct archive_write_disk *a)
416 {
417 	int oerrno, fd;
418 	mode_t mode;
419 
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;
423 
424 	fd = __archive_mkstemp(a->tmpname);
425 	if (fd == -1)
426 		return -1;
427 
428 	mode = a->mode & 0777 & ~a->user_umask;
429 	if (fchmod(fd, mode) == -1) {
430 		oerrno = errno;
431 		close(fd);
432 		errno = oerrno;
433 		return -1;
434 	}
435 	return fd;
436 }
437 
438 static int
439 la_opendirat(int fd, const char *path) {
440 	const int flags = O_CLOEXEC
441 #if defined(O_BINARY)
442 	    | O_BINARY
443 #endif
444 #if defined(O_DIRECTORY)
445 	    | O_DIRECTORY
446 #endif
447 #if defined(O_PATH)
448 	    | O_PATH
449 #elif defined(O_SEARCH)
450 	    | O_SEARCH
451 #elif defined(__FreeBSD__) && defined(O_EXEC)
452 	    | O_EXEC
453 #else
454 	    | O_RDONLY
455 #endif
456 	    ;
457 
458 #if !defined(HAVE_OPENAT)
459 	if (fd != AT_FDCWD) {
460 		errno = ENOTSUP;
461 		return (-1);
462 	} else
463 		return (open(path, flags));
464 #else
465 	return (openat(fd, path, flags));
466 #endif
467 }
468 
469 static int
470 la_verify_filetype(mode_t mode, __LA_MODE_T filetype) {
471 	int ret = 0;
472 
473 	switch (filetype) {
474 	case AE_IFREG:
475 		ret = (S_ISREG(mode));
476 		break;
477 	case AE_IFDIR:
478 		ret = (S_ISDIR(mode));
479 		break;
480 	case AE_IFLNK:
481 		ret = (S_ISLNK(mode));
482 		break;
483 	case AE_IFSOCK:
484 		ret = (S_ISSOCK(mode));
485 		break;
486 	case AE_IFCHR:
487 		ret = (S_ISCHR(mode));
488 		break;
489 	case AE_IFBLK:
490 		ret = (S_ISBLK(mode));
491 		break;
492 	case AE_IFIFO:
493 		ret = (S_ISFIFO(mode));
494 		break;
495 	default:
496 		break;
497 	}
498 
499 	return (ret);
500 }
501 
502 static int
503 lazy_stat(struct archive_write_disk *a)
504 {
505 	if (a->pst != NULL) {
506 		/* Already have stat() data available. */
507 		return (ARCHIVE_OK);
508 	}
509 #ifdef HAVE_FSTAT
510 	if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
511 		a->pst = &a->st;
512 		return (ARCHIVE_OK);
513 	}
514 #endif
515 	/*
516 	 * XXX At this point, symlinks should not be hit, otherwise
517 	 * XXX a race occurred.  Do we want to check explicitly for that?
518 	 */
519 	if (lstat(a->name, &a->st) == 0) {
520 		a->pst = &a->st;
521 		return (ARCHIVE_OK);
522 	}
523 	archive_set_error(&a->archive, errno, "Couldn't stat file");
524 	return (ARCHIVE_WARN);
525 }
526 
527 static struct archive_vtable *
528 archive_write_disk_vtable(void)
529 {
530 	static struct archive_vtable av;
531 	static int inited = 0;
532 
533 	if (!inited) {
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;
542 		inited = 1;
543 	}
544 	return (&av);
545 }
546 
547 static int64_t
548 _archive_write_disk_filter_bytes(struct archive *_a, int n)
549 {
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);
554 	return (-1);
555 }
556 
557 
558 int
559 archive_write_disk_set_options(struct archive *_a, int flags)
560 {
561 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
562 
563 	a->flags = flags;
564 	return (ARCHIVE_OK);
565 }
566 
567 
568 /*
569  * Extract this entry to disk.
570  *
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.
577  *
578  */
579 static int
580 _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
581 {
582 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
583 	struct fixup_entry *fe;
584 	const char *linkname;
585 	int ret, r;
586 
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)
594 			return (r);
595 	}
596 
597 	/* Set up for this particular entry. */
598 	a->pst = NULL;
599 	a->current_fixup = NULL;
600 	a->deferred = 0;
601 	if (a->entry) {
602 		archive_entry_free(a->entry);
603 		a->entry = NULL;
604 	}
605 	a->entry = archive_entry_clone(entry);
606 	a->fd = -1;
607 	a->fd_offset = 0;
608 	a->offset = 0;
609 	a->restore_pwd = -1;
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);
614 	else
615 		a->filesize = -1;
616 	archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
617 	a->name = a->_name_data.s;
618 	archive_clear_error(&a->archive);
619 
620 	/*
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/.".
624 	 */
625 	ret = cleanup_pathname(a);
626 	if (ret != ARCHIVE_OK)
627 		return (ret);
628 
629 	/*
630 	 * Check if we have a hardlink that points to itself.
631 	 */
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",
636 		    a->name);
637 		return (ARCHIVE_WARN);
638 	}
639 
640 	/*
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
644 	 * reason.
645 	 */
646 	umask(a->user_umask = umask(0));
647 
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. */
652 		/*
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
664 		 * to keep track.
665 		 */
666 		if (a->mode & S_ISGID)
667 			a->todo |= TODO_SGID | TODO_SGID_CHECK;
668 		/*
669 		 * Verifying the SUID is simpler, but can still be
670 		 * done in multiple ways, hence the separate "check" bit.
671 		 */
672 		if (a->mode & S_ISUID)
673 			a->todo |= TODO_SUID | TODO_SUID_CHECK;
674 	} else {
675 		/*
676 		 * User didn't request full permissions, so don't
677 		 * restore SUID, SGID bits and obey umask.
678 		 */
679 		a->mode &= ~S_ISUID;
680 		a->mode &= ~S_ISGID;
681 		a->mode &= ~S_ISVTX;
682 		a->mode &= ~a->user_umask;
683 	}
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
690 		/*
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.
694 		 */
695 		size_t metadata_size;
696 
697 		if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
698 		    archive_entry_mac_metadata(a->entry,
699 		    &metadata_size) == NULL || metadata_size == 0)
700 #endif
701 #if ARCHIVE_ACL_LIBRICHACL
702 		/*
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.
706 		 */
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;
713 			size_t attr_size;
714 			int i = archive_entry_xattr_reset(a->entry);
715 			while (i--) {
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) {
721 					extract_acls = 0;
722 					break;
723 				}
724 			}
725 		}
726 		if (extract_acls)
727 #endif
728 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
729 		{
730 #endif
731 		if (archive_entry_filetype(a->entry) == AE_IFDIR)
732 			a->deferred |= TODO_ACLS;
733 		else
734 			a->todo |= TODO_ACLS;
735 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
736 		}
737 #endif
738 	}
739 	if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
740 		if (archive_entry_filetype(a->entry) == AE_IFDIR)
741 			a->deferred |= TODO_MAC_METADATA;
742 		else
743 			a->todo |= TODO_MAC_METADATA;
744 	}
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;
752 		}
753 	}
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;
758 	}
759 	{
760 		const char *p;
761 
762 		/* Check if the current file name is a type of the
763 		 * resource fork file. */
764 		p = strrchr(a->name, '/');
765 		if (p == NULL)
766 			p = a->name;
767 		else
768 			p++;
769 		if (p[0] == '.' && p[1] == '_') {
770 			/* Do not compress "._XXX" files. */
771 			a->todo &= ~TODO_HFS_COMPRESSION;
772 			if (a->filesize > 0)
773 				a->todo |= TODO_APPLEDOUBLE;
774 		}
775 	}
776 #endif
777 
778 	if (a->flags & ARCHIVE_EXTRACT_XATTR) {
779 #if ARCHIVE_XATTR_DARWIN
780 		/*
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.
784 		 */
785 		size_t metadata_size;
786 
787 		if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
788 		    archive_entry_mac_metadata(a->entry,
789 		    &metadata_size) == NULL || metadata_size == 0)
790 #endif
791 		a->todo |= TODO_XATTR;
792 	}
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)
798 			return (ret);
799 	}
800 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
801 	/* If path exceeds PATH_MAX, shorten the path. */
802 	edit_deep_directories(a);
803 #endif
804 
805 	ret = restore_entry(a);
806 
807 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
808 	/*
809 	 * Check if the filesystem the file is restoring on supports
810 	 * HFS+ Compression. If not, cancel HFS+ Compression.
811 	 */
812 	if (a->todo | TODO_HFS_COMPRESSION) {
813 		/*
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.
820 		 */
821 		if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
822 			a->todo &= ~TODO_HFS_COMPRESSION;
823 	}
824 #endif
825 
826 	/*
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.
834 	 */
835 
836 #ifdef HAVE_FCHDIR
837 	/* If we changed directory above, restore it here. */
838 	if (a->restore_pwd >= 0) {
839 		r = fchdir(a->restore_pwd);
840 		if (r != 0) {
841 			archive_set_error(&a->archive, errno,
842 			    "chdir() failure");
843 			ret = ARCHIVE_FATAL;
844 		}
845 		close(a->restore_pwd);
846 		a->restore_pwd = -1;
847 	}
848 #endif
849 
850 	/*
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.
855 	 */
856 	if (a->deferred & TODO_MODE) {
857 		fe = current_fixup(a, archive_entry_pathname(entry));
858 		if (fe == NULL)
859 			return (ARCHIVE_FATAL);
860 		fe->filetype = archive_entry_filetype(entry);
861 		fe->fixup |= TODO_MODE_BASE;
862 		fe->mode = a->mode;
863 	}
864 
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));
869 		if (fe == NULL)
870 			return (ARCHIVE_FATAL);
871 		fe->filetype = archive_entry_filetype(entry);
872 		fe->mode = a->mode;
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);
877 		} else {
878 			/* If atime is unset, use start time. */
879 			fe->atime = a->start_time;
880 			fe->atime_nanos = 0;
881 		}
882 		if (archive_entry_mtime_is_set(entry)) {
883 			fe->mtime = archive_entry_mtime(entry);
884 			fe->mtime_nanos = archive_entry_mtime_nsec(entry);
885 		} else {
886 			/* If mtime is unset, use start time. */
887 			fe->mtime = a->start_time;
888 			fe->mtime_nanos = 0;
889 		}
890 		if (archive_entry_birthtime_is_set(entry)) {
891 			fe->birthtime = archive_entry_birthtime(entry);
892 			fe->birthtime_nanos = archive_entry_birthtime_nsec(
893 			    entry);
894 		} else {
895 			/* If birthtime is unset, use mtime. */
896 			fe->birthtime = fe->mtime;
897 			fe->birthtime_nanos = fe->mtime_nanos;
898 		}
899 	}
900 
901 	if (a->deferred & TODO_ACLS) {
902 		fe = current_fixup(a, archive_entry_pathname(entry));
903 		if (fe == NULL)
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));
908 	}
909 
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));
916 			if (fe == NULL)
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,
922 				    metadata_size);
923 				fe->mac_metadata_size = metadata_size;
924 				fe->fixup |= TODO_MAC_METADATA;
925 			}
926 		}
927 	}
928 
929 	if (a->deferred & TODO_FFLAGS) {
930 		fe = current_fixup(a, archive_entry_pathname(entry));
931 		if (fe == NULL)
932 			return (ARCHIVE_FATAL);
933 		fe->filetype = archive_entry_filetype(entry);
934 		fe->fixup |= TODO_FFLAGS;
935 		/* TODO: Complete this.. defer fflags from below. */
936 	}
937 
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;
941 	/*
942 	 * If it's not open, tell our client not to try writing.
943 	 * In particular, dirs, links, etc, don't get written to.
944 	 */
945 	if (a->fd < 0) {
946 		archive_entry_set_size(entry, 0);
947 		a->filesize = 0;
948 	}
949 
950 	return (ret);
951 }
952 
953 int
954 archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
955 {
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;
962 	return (ARCHIVE_OK);
963 }
964 
965 static ssize_t
966 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
967 {
968 	uint64_t start_size = size;
969 	ssize_t bytes_written = 0;
970 	ssize_t block_size = 0, bytes_to_write;
971 
972 	if (size == 0)
973 		return (ARCHIVE_OK);
974 
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);
979 	}
980 
981 	if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
982 #if HAVE_STRUCT_STAT_ST_BLKSIZE
983 		int r;
984 		if ((r = lazy_stat(a)) != ARCHIVE_OK)
985 			return (r);
986 		block_size = a->pst->st_blksize;
987 #else
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;
991 #endif
992 	}
993 
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);
997 
998 	/* Write the data. */
999 	while (size > 0) {
1000 		if (block_size == 0) {
1001 			bytes_to_write = size;
1002 		} else {
1003 			/* We're sparsifying the file. */
1004 			const char *p, *end;
1005 			int64_t block_end;
1006 
1007 			/* Skip leading zero bytes. */
1008 			for (p = buff, end = buff + size; p < end; ++p) {
1009 				if (*p != '\0')
1010 					break;
1011 			}
1012 			a->offset += p - buff;
1013 			size -= p - buff;
1014 			buff = p;
1015 			if (size == 0)
1016 				break;
1017 
1018 			/* Calculate next block boundary after offset. */
1019 			block_end
1020 			    = (a->offset / block_size + 1) * block_size;
1021 
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;
1027 		}
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,
1032 				    "Seek failed");
1033 				return (ARCHIVE_FATAL);
1034 			}
1035 			a->fd_offset = a->offset;
1036 		}
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);
1041 		}
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;
1047 	}
1048 	return (start_size - size);
1049 }
1050 
1051 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
1052 	&& defined(HAVE_ZLIB_H)
1053 
1054 /*
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.
1058  */
1059 static int
1060 hfs_set_compressed_fflag(struct archive_write_disk *a)
1061 {
1062 	int r;
1063 
1064 	if ((r = lazy_stat(a)) != ARCHIVE_OK)
1065 		return (r);
1066 
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);
1072 	}
1073 	return (ARCHIVE_OK);
1074 }
1075 
1076 /*
1077  * HFS+ Compression decmpfs
1078  *
1079  *     +------------------------------+ +0
1080  *     |      Magic(LE 4 bytes)       |
1081  *     +------------------------------+
1082  *     |      Type(LE 4 bytes)        |
1083  *     +------------------------------+
1084  *     | Uncompressed size(LE 8 bytes)|
1085  *     +------------------------------+ +16
1086  *     |                              |
1087  *     |       Compressed data        |
1088  *     |  (Placed only if Type == 3)  |
1089  *     |                              |
1090  *     +------------------------------+  +3802 = MAX_DECMPFS_XATTR_SIZE
1091  *
1092  *  Type is 3: decmpfs has compressed data.
1093  *  Type is 4: Resource Fork has compressed data.
1094  */
1095 /*
1096  * Write "com.apple.decmpfs"
1097  */
1098 static int
1099 hfs_write_decmpfs(struct archive_write_disk *a)
1100 {
1101 	int r;
1102 	uint32_t compression_type;
1103 
1104 	r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1105 	    a->decmpfs_attr_size, 0, 0);
1106 	if (r < 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);
1115 	}
1116 	return (ARCHIVE_OK);
1117 }
1118 
1119 /*
1120  * HFS+ Compression Resource Fork
1121  *
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  * |   +-----------------------------+  --+
1132  * |   |                             |
1133  * |   |      ..................     |
1134  * |   |                             |
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  *     +-----------------------------+
1142  *     |                             |
1143  *     |      ..................     |
1144  *     |                             |
1145  *     +-----------------------------+
1146  *     |   Compressed data(n bytes)  |  Block (Block count -1)
1147  *     +-----------------------------+
1148  *     |      Footer(50 bytes)       |
1149  *     +-----------------------------+
1150  *
1151  */
1152 /*
1153  * Write the header of "com.apple.ResourceFork"
1154  */
1155 static int
1156 hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1157     size_t bytes, uint32_t position)
1158 {
1159 	int ret;
1160 
1161 	ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1162 	    position, a->rsrc_xattr_options);
1163 	if (ret < 0) {
1164 		archive_set_error(&a->archive, errno,
1165 		    "Cannot restore xattr: %s at %u pos %u bytes",
1166 		    XATTR_RESOURCEFORK_NAME,
1167 		    (unsigned)position,
1168 		    (unsigned)bytes);
1169 		return (ARCHIVE_WARN);
1170 	}
1171 	a->rsrc_xattr_options &= ~XATTR_CREATE;
1172 	return (ARCHIVE_OK);
1173 }
1174 
1175 static int
1176 hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1177 {
1178 	int ret;
1179 
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;
1184 	return (ret);
1185 }
1186 
1187 static int
1188 hfs_write_resource_fork_header(struct archive_write_disk *a)
1189 {
1190 	unsigned char *buff;
1191 	uint32_t rsrc_bytes;
1192 	uint32_t rsrc_header_bytes;
1193 
1194 	/*
1195 	 * Write resource fork header + block info.
1196 	 */
1197 	buff = a->resource_fork;
1198 	rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1199 	rsrc_header_bytes =
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);
1210 }
1211 
1212 static size_t
1213 hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1214 {
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,
1222 		0x00, 0x00
1223 	};
1224 	if (buff_size < sizeof(rsrc_footer))
1225 		return (0);
1226 	memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1227 	return (sizeof(rsrc_footer));
1228 }
1229 
1230 static int
1231 hfs_reset_compressor(struct archive_write_disk *a)
1232 {
1233 	int ret;
1234 
1235 	if (a->stream_valid)
1236 		ret = deflateReset(&a->stream);
1237 	else
1238 		ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1239 
1240 	if (ret != Z_OK) {
1241 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1242 		    "Failed to initialize compressor");
1243 		return (ARCHIVE_FATAL);
1244 	} else
1245 		a->stream_valid = 1;
1246 
1247 	return (ARCHIVE_OK);
1248 }
1249 
1250 static int
1251 hfs_decompress(struct archive_write_disk *a)
1252 {
1253 	uint32_t *block_info;
1254 	unsigned int block_count;
1255 	uint32_t data_pos, data_size;
1256 	ssize_t r;
1257 	ssize_t bytes_written, bytes_to_write;
1258 	unsigned char *b;
1259 
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);
1272 		}
1273 		if (a->compressed_buffer[0] == 0xff) {
1274 			bytes_to_write = data_size -1;
1275 			b = a->compressed_buffer + 1;
1276 		} else {
1277 			uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1278 			int zr;
1279 
1280 			zr = uncompress((Bytef *)a->uncompressed_buffer,
1281 			    &dest_len, a->compressed_buffer, data_size);
1282 			if (zr != Z_OK) {
1283 				archive_set_error(&a->archive,
1284 				    ARCHIVE_ERRNO_MISC,
1285 				    "Failed to decompress resource fork");
1286 				return (ARCHIVE_WARN);
1287 			}
1288 			bytes_to_write = dest_len;
1289 			b = (unsigned char *)a->uncompressed_buffer;
1290 		}
1291 		do {
1292 			bytes_written = write(a->fd, b, bytes_to_write);
1293 			if (bytes_written < 0) {
1294 				archive_set_error(&a->archive, errno,
1295 				    "Write failed");
1296 				return (ARCHIVE_WARN);
1297 			}
1298 			bytes_to_write -= bytes_written;
1299 			b += bytes_written;
1300 		} while (bytes_to_write > 0);
1301 	}
1302 	r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1303 	if (r == -1)  {
1304 		archive_set_error(&a->archive, errno,
1305 		    "Failed to remove resource fork");
1306 		return (ARCHIVE_WARN);
1307 	}
1308 	return (ARCHIVE_OK);
1309 }
1310 
1311 static int
1312 hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1313     size_t size)
1314 {
1315 	unsigned char *buffer_compressed;
1316 	size_t bytes_compressed;
1317 	size_t bytes_used;
1318 	int ret;
1319 
1320 	ret = hfs_reset_compressor(a);
1321 	if (ret != ARCHIVE_OK)
1322 		return (ret);
1323 
1324 	if (a->compressed_buffer == NULL) {
1325 		size_t block_size;
1326 
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);
1334 		}
1335 		a->compressed_buffer_size = block_size;
1336 		a->compressed_buffer_remaining = block_size;
1337 	}
1338 
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;
1345 	do {
1346 		ret = deflate(&a->stream, Z_FINISH);
1347 		switch (ret) {
1348 		case Z_OK:
1349 		case Z_STREAM_END:
1350 			break;
1351 		default:
1352 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1353 			    "Failed to compress data");
1354 			return (ARCHIVE_FAILED);
1355 		}
1356 	} while (ret == Z_OK);
1357 	bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1358 
1359 	/*
1360 	 * If the compressed size is larger than the original size,
1361 	 * throw away compressed data, use uncompressed data instead.
1362 	 */
1363 	if (bytes_compressed > size) {
1364 		buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1365 		memcpy(buffer_compressed + 1, buff, size);
1366 		bytes_compressed = size + 1;
1367 	}
1368 	a->compressed_buffer_remaining -= bytes_compressed;
1369 
1370 	/*
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.
1374 	 */
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],
1379 		    CMP_XATTR);
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;
1384 		/*
1385 		 * Finish HFS+ Compression.
1386 		 * - Write the decmpfs xattr.
1387 		 * - Set the UF_COMPRESSED file flag.
1388 		 */
1389 		ret = hfs_write_decmpfs(a);
1390 		if (ret == ARCHIVE_OK)
1391 			ret = hfs_set_compressed_fflag(a);
1392 		return (ret);
1393 	}
1394 
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;
1400 
1401 	/*
1402 	 * Write the compressed data to the resource fork.
1403 	 */
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)
1408 			return (ret);
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,
1413 			    bytes_used);
1414 		else
1415 			memcpy(a->compressed_buffer,
1416 			    a->compressed_buffer + COMPRESSED_W_SIZE,
1417 			    bytes_used);
1418 	}
1419 	a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1420 
1421 	/*
1422 	 * If the current block is the last block, write the remaining
1423 	 * compressed data and the resource fork footer.
1424 	 */
1425 	if (a->file_remaining_bytes == 0) {
1426 		size_t rsrc_size;
1427 		int64_t bk;
1428 
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;
1435 
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);
1441 		bk += bk >> 7;
1442 		if (bk > HFS_BLOCKS(a->filesize))
1443 			return hfs_decompress(a);
1444 		/*
1445 		 * Write the resourcefork header.
1446 		 */
1447 		if (ret == ARCHIVE_OK)
1448 			ret = hfs_write_resource_fork_header(a);
1449 		/*
1450 		 * Finish HFS+ Compression.
1451 		 * - Write the decmpfs xattr.
1452 		 * - Set the UF_COMPRESSED file flag.
1453 		 */
1454 		if (ret == ARCHIVE_OK)
1455 			ret = hfs_write_decmpfs(a);
1456 		if (ret == ARCHIVE_OK)
1457 			ret = hfs_set_compressed_fflag(a);
1458 	}
1459 	return (ret);
1460 }
1461 
1462 static ssize_t
1463 hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1464     size_t size)
1465 {
1466 	const char *buffer_to_write;
1467 	size_t bytes_to_write;
1468 	int ret;
1469 
1470 	if (a->decmpfs_block_count == (unsigned)-1) {
1471 		void *new_block;
1472 		size_t new_size;
1473 		unsigned int block_count;
1474 
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);
1482 			}
1483 			a->decmpfs_header_p = new_block;
1484 		}
1485 		a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1486 		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1487 		    DECMPFS_MAGIC);
1488 		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1489 		    CMP_RESOURCE_FORK);
1490 		archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1491 		    a->filesize);
1492 
1493 		/* Calculate a block count of the file. */
1494 		block_count =
1495 		    (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1496 			MAX_DECMPFS_BLOCK_SIZE;
1497 		/*
1498 		 * Allocate buffer for resource fork.
1499 		 * Set up related pointers;
1500 		 */
1501 		new_size =
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);
1512 			}
1513 			a->resource_fork_allocated_size = new_size;
1514 			a->resource_fork = new_block;
1515 		}
1516 
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);
1524 			}
1525 			a->uncompressed_buffer = new_block;
1526 		}
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;
1530 
1531 		/*
1532 		 * Set up a resource fork.
1533 		 */
1534 		a->rsrc_xattr_options = XATTR_CREATE;
1535 		/* Get the position where we are going to set a bunch
1536 		 * of block info. */
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
1542 		 * data. */
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;
1547 	}
1548 
1549 	/* Ignore redundant bytes. */
1550 	if (a->file_remaining_bytes == 0)
1551 		return ((ssize_t)size);
1552 
1553 	/* Do not overrun a block size. */
1554 	if (size > a->block_remaining_bytes)
1555 		bytes_to_write = a->block_remaining_bytes;
1556 	else
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;
1561 
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;
1566 	else {
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;
1571 	}
1572 	a->block_remaining_bytes -= bytes_to_write;
1573 	a->file_remaining_bytes -= bytes_to_write;
1574 
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);
1578 		if (ret < 0)
1579 			return (ret);
1580 		a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1581 	}
1582 	/* Ignore redundant bytes. */
1583 	if (a->file_remaining_bytes == 0)
1584 		return ((ssize_t)size);
1585 	return (bytes_to_write);
1586 }
1587 
1588 static ssize_t
1589 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1590     size_t size)
1591 {
1592 	uint64_t start_size = size;
1593 	ssize_t bytes_written = 0;
1594 	ssize_t bytes_to_write;
1595 
1596 	if (size == 0)
1597 		return (ARCHIVE_OK);
1598 
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);
1603 	}
1604 
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);
1608 
1609 	/* Write the data. */
1610 	while (size > 0) {
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,
1616 			    "Seek failed");
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];
1621 
1622 			memset(nullblock, 0, sizeof(nullblock));
1623 			while (skip > 0) {
1624 				if (skip > (int64_t)sizeof(nullblock))
1625 					bytes_written = hfs_write_decmpfs_block(
1626 					    a, nullblock, sizeof(nullblock));
1627 				else
1628 					bytes_written = hfs_write_decmpfs_block(
1629 					    a, nullblock, skip);
1630 				if (bytes_written < 0) {
1631 					archive_set_error(&a->archive, errno,
1632 					    "Write failed");
1633 					return (ARCHIVE_WARN);
1634 				}
1635 				skip -= bytes_written;
1636 			}
1637 
1638 			a->fd_offset = a->offset;
1639 		}
1640 		bytes_written =
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;
1649 	}
1650 	return (start_size - size);
1651 }
1652 #else
1653 static ssize_t
1654 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1655     size_t size)
1656 {
1657 	return (write_data_block(a, buff, size));
1658 }
1659 #endif
1660 
1661 static ssize_t
1662 _archive_write_disk_data_block(struct archive *_a,
1663     const void *buff, size_t size, int64_t offset)
1664 {
1665 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1666 	ssize_t r;
1667 
1668 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1669 	    ARCHIVE_STATE_DATA, "archive_write_data_block");
1670 
1671 	a->offset = offset;
1672 	if (a->todo & TODO_HFS_COMPRESSION)
1673 		r = hfs_write_data_block(a, buff, size);
1674 	else
1675 		r = write_data_block(a, buff, size);
1676 	if (r < ARCHIVE_OK)
1677 		return (r);
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);
1683 	}
1684 #if ARCHIVE_VERSION_NUMBER < 3999000
1685 	return (ARCHIVE_OK);
1686 #else
1687 	return (size);
1688 #endif
1689 }
1690 
1691 static ssize_t
1692 _archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1693 {
1694 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1695 
1696 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1697 	    ARCHIVE_STATE_DATA, "archive_write_data");
1698 
1699 	if (a->todo & TODO_HFS_COMPRESSION)
1700 		return (hfs_write_data_block(a, buff, size));
1701 	return (write_data_block(a, buff, size));
1702 }
1703 
1704 static int
1705 _archive_write_disk_finish_entry(struct archive *_a)
1706 {
1707 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1708 	int ret = ARCHIVE_OK;
1709 
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);
1716 
1717 	/* Pad or truncate file to the right size. */
1718 	if (a->fd < 0) {
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) {
1727 		char null_d[1024];
1728 		ssize_t r;
1729 
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));
1736 			else
1737 				r = hfs_write_data_block(
1738 				    a, null_d, a->file_remaining_bytes);
1739 			if (r < 0)
1740 				return ((int)r);
1741 		}
1742 #endif
1743 	} else {
1744 #if HAVE_FTRUNCATE
1745 		if (ftruncate(a->fd, a->filesize) == -1 &&
1746 		    a->filesize == 0) {
1747 			archive_set_error(&a->archive, errno,
1748 			    "File size could not be restored");
1749 			return (ARCHIVE_FAILED);
1750 		}
1751 #endif
1752 		/*
1753 		 * Not all platforms implement the XSI option to
1754 		 * extend files via ftruncate.  Stat() the file again
1755 		 * to see what happened.
1756 		 */
1757 		a->pst = NULL;
1758 		if ((ret = lazy_stat(a)) != ARCHIVE_OK)
1759 			return (ret);
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,
1766 				    "Seek failed");
1767 				return (ARCHIVE_FATAL);
1768 			}
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);
1773 			}
1774 			a->pst = NULL;
1775 		}
1776 	}
1777 
1778 	/* Restore metadata. */
1779 
1780 	/*
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.
1784 	 */
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;
1792 		}
1793 		if (r2 < ret) ret = r2;
1794 	}
1795 
1796 	/*
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?
1799 	 */
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));
1804 	}
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));
1811 	 }
1812 
1813 	/*
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.
1817 	 */
1818 	if (a->todo & TODO_OWNER) {
1819 		int r2 = set_ownership(a);
1820 		if (r2 < ret) ret = r2;
1821 	}
1822 
1823 	/*
1824 	 * HYPOTHESIS:
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.
1830 	 */
1831 	if (a->user_uid != 0 &&
1832 	    (a->todo & TODO_XATTR)) {
1833 		int r2 = set_xattrs(a);
1834 		if (r2 < ret) ret = r2;
1835 	}
1836 
1837 	/*
1838 	 * set_mode must precede ACLs on systems such as Solaris and
1839 	 * FreeBSD where setting the mode implicitly clears extended ACLs
1840 	 */
1841 	if (a->todo & TODO_MODE) {
1842 		int r2 = set_mode(a, a->mode);
1843 		if (r2 < ret) ret = r2;
1844 	}
1845 
1846 	/*
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.
1851 	 */
1852 	if (a->user_uid == 0 &&
1853 	    (a->todo & TODO_XATTR)) {
1854 		int r2 = set_xattrs(a);
1855 		if (r2 < ret) ret = r2;
1856 	}
1857 
1858 	/*
1859 	 * Some flags prevent file modification; they must be restored after
1860 	 * file contents are written.
1861 	 */
1862 	if (a->todo & TODO_FFLAGS) {
1863 		int r2 = set_fflags(a);
1864 		if (r2 < ret) ret = r2;
1865 	}
1866 
1867 	/*
1868 	 * Time must follow most other metadata;
1869 	 * otherwise atime will get changed.
1870 	 */
1871 	if (a->todo & TODO_TIMES) {
1872 		int r2 = set_times_from_entry(a);
1873 		if (r2 < ret) ret = r2;
1874 	}
1875 
1876 	/*
1877 	 * Mac extended metadata includes ACLs.
1878 	 */
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;
1887 		}
1888 	}
1889 
1890 	/*
1891 	 * ACLs must be restored after timestamps because there are
1892 	 * ACLs that prevent attribute changes (including time).
1893 	 */
1894 	if (a->todo & TODO_ACLS) {
1895 		int r2;
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;
1901 	}
1902 
1903 finish_metadata:
1904 	/* If there's an fd, we can close it now. */
1905 	if (a->fd >= 0) {
1906 		close(a->fd);
1907 		a->fd = -1;
1908 		if (a->tmpname) {
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;
1913 				unlink(a->tmpname);
1914 			}
1915 			a->tmpname = NULL;
1916 		}
1917 	}
1918 	/* If there's an entry, we can release it now. */
1919 	archive_entry_free(a->entry);
1920 	a->entry = NULL;
1921 	a->archive.state = ARCHIVE_STATE_HEADER;
1922 	return (ret);
1923 }
1924 
1925 int
1926 archive_write_disk_set_group_lookup(struct archive *_a,
1927     void *private_data,
1928     la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1929     void (*cleanup_gid)(void *private))
1930 {
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");
1934 
1935 	if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1936 		(a->cleanup_gid)(a->lookup_gid_data);
1937 
1938 	a->lookup_gid = lookup_gid;
1939 	a->cleanup_gid = cleanup_gid;
1940 	a->lookup_gid_data = private_data;
1941 	return (ARCHIVE_OK);
1942 }
1943 
1944 int
1945 archive_write_disk_set_user_lookup(struct archive *_a,
1946     void *private_data,
1947     int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1948     void (*cleanup_uid)(void *private))
1949 {
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");
1953 
1954 	if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1955 		(a->cleanup_uid)(a->lookup_uid_data);
1956 
1957 	a->lookup_uid = lookup_uid;
1958 	a->cleanup_uid = cleanup_uid;
1959 	a->lookup_uid_data = private_data;
1960 	return (ARCHIVE_OK);
1961 }
1962 
1963 int64_t
1964 archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1965 {
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");
1969        if (a->lookup_gid)
1970                return (a->lookup_gid)(a->lookup_gid_data, name, id);
1971        return (id);
1972 }
1973 
1974 int64_t
1975 archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1976 {
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");
1980 	if (a->lookup_uid)
1981 		return (a->lookup_uid)(a->lookup_uid_data, name, id);
1982 	return (id);
1983 }
1984 
1985 /*
1986  * Create a new archive_write_disk object and initialize it with global state.
1987  */
1988 struct archive *
1989 archive_write_disk_new(void)
1990 {
1991 	struct archive_write_disk *a;
1992 
1993 	a = (struct archive_write_disk *)calloc(1, sizeof(*a));
1994 	if (a == NULL)
1995 		return (NULL);
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));
2003 #ifdef HAVE_GETEUID
2004 	a->user_uid = geteuid();
2005 #endif /* HAVE_GETEUID */
2006 	if (archive_string_ensure(&a->path_safe, 512) == NULL) {
2007 		free(a);
2008 		return (NULL);
2009 	}
2010 #ifdef HAVE_ZLIB_H
2011 	a->decmpfs_compression_level = 5;
2012 #endif
2013 	return (&a->archive);
2014 }
2015 
2016 
2017 /*
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
2023  * at that time.
2024  */
2025 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
2026 static void
2027 edit_deep_directories(struct archive_write_disk *a)
2028 {
2029 	int ret;
2030 	char *tail = a->name;
2031 
2032 	/* If path is short, avoid the open() below. */
2033 	if (strlen(tail) < PATH_MAX)
2034 		return;
2035 
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)
2040 		return;
2041 
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 != '/')
2047 			tail--;
2048 		/* Exit if we find a too-long path component. */
2049 		if (tail <= a->name)
2050 			return;
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)
2058 			return;
2059 		tail++;
2060 		/* The chdir() succeeded; we've now shortened the path. */
2061 		a->name = tail;
2062 	}
2063 	return;
2064 }
2065 #endif
2066 
2067 /*
2068  * The main restore function.
2069  */
2070 static int
2071 restore_entry(struct archive_write_disk *a)
2072 {
2073 	int ret = ARCHIVE_OK, en;
2074 
2075 	if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
2076 		/*
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.
2083 		 */
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. */
2088 			a->pst = NULL;
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. */
2093 			a->pst = NULL;
2094 		} else {
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);
2099 		}
2100 	}
2101 
2102 	/* Try creating it first; if this fails, we'll try to recover. */
2103 	en = create_filesystem_object(a);
2104 
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);
2111 	}
2112 
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);
2118 	}
2119 
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. */
2125 			a->todo = 0;
2126 		}
2127 		archive_entry_unset_size(a->entry);
2128 		return (ARCHIVE_OK);
2129 	}
2130 
2131 	/*
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.
2137 	 */
2138 	if (en == EISDIR) {
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);
2144 		}
2145 		a->pst = NULL;
2146 		/* Try again. */
2147 		en = create_filesystem_object(a);
2148 	} else if (en == EEXIST) {
2149 		/*
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.
2152 		 */
2153 		int r = 0;
2154 		/*
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.
2158 		 */
2159 		if (S_ISDIR(a->mode))
2160 			r = la_stat(a->name, &a->st);
2161 		/*
2162 		 * If it's not a dir (or it's a broken symlink),
2163 		 * then don't follow it.
2164 		 */
2165 		if (r != 0 || !S_ISDIR(a->mode))
2166 			r = lstat(a->name, &a->st);
2167 		if (r != 0) {
2168 			archive_set_error(&a->archive, errno,
2169 			    "Can't stat existing object");
2170 			return (ARCHIVE_FAILED);
2171 		}
2172 
2173 		/*
2174 		 * NO_OVERWRITE_NEWER doesn't apply to directories.
2175 		 */
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);
2181 			}
2182 		}
2183 
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);
2191 		}
2192 
2193 		if (!S_ISDIR(a->st.st_mode)) {
2194 			if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2195 				(void)clear_nochange_fflags(a);
2196 
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;
2204 				}
2205 				a->pst = NULL;
2206 				en = 0;
2207 			} else {
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 "
2212 					    "object");
2213 					return (ARCHIVE_FAILED);
2214 				}
2215 				a->pst = NULL;
2216 				/* Try again. */
2217 				en = create_filesystem_object(a);
2218 			}
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);
2227 			}
2228 			/* Try again. */
2229 			en = create_filesystem_object(a);
2230 		} else {
2231 			/*
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.
2237 			 */
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. */
2243 		}
2244 	}
2245 
2246 	if (en) {
2247 		/* Everything failed; give up here. */
2248 		if ((&a->archive)->error == NULL)
2249 			archive_set_error(&a->archive, en, "Can't create '%s'",
2250 			    a->name);
2251 		return (ARCHIVE_FAILED);
2252 	}
2253 
2254 	a->pst = NULL; /* Cached stat data no longer valid. */
2255 	return (ret);
2256 }
2257 
2258 /*
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.
2262  */
2263 static int
2264 create_filesystem_object(struct archive_write_disk *a)
2265 {
2266 	/* Create the entry. */
2267 	const char *linkname;
2268 	mode_t final_mode, mode;
2269 	int r;
2270 	/* these for check_symlinks_fsobj */
2271 	char *linkname_copy;	/* non-const copy of linkname */
2272 	struct stat st;
2273 	struct archive_string error_string;
2274 	int error_number;
2275 
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) {
2280 #if !HAVE_LINK
2281 		return (EPERM);
2282 #else
2283 		archive_string_init(&error_string);
2284 		linkname_copy = strdup(linkname);
2285 		if (linkname_copy == NULL) {
2286 		    return (EPERM);
2287 		}
2288 		/*
2289 		 * TODO: consider using the cleaned-up path as the link
2290 		 * target?
2291 		 */
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",
2296 			    error_string.s);
2297 			free(linkname_copy);
2298 			archive_string_free(&error_string);
2299 			/*
2300 			 * EPERM is more appropriate than error_number for our
2301 			 * callers
2302 			 */
2303 			return (EPERM);
2304 		}
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",
2309 			    error_string.s);
2310 			free(linkname_copy);
2311 			archive_string_free(&error_string);
2312 			/*
2313 			 * EPERM is more appropriate than error_number for our
2314 			 * callers
2315 			 */
2316 			return (EPERM);
2317 		}
2318 		free(linkname_copy);
2319 		archive_string_free(&error_string);
2320 		/*
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).
2324 		 */
2325 		if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2326 			unlink(a->name);
2327 #ifdef HAVE_LINKAT
2328 		r = linkat(AT_FDCWD, linkname, AT_FDCWD, a->name,
2329 		    0) ? errno : 0;
2330 #else
2331 		r = link(linkname, a->name) ? errno : 0;
2332 #endif
2333 		/*
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.
2337 		 *
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.
2344 		 */
2345 		if (r == 0 && a->filesize <= 0) {
2346 			a->todo = 0;
2347 			a->deferred = 0;
2348 		} else if (r == 0 && a->filesize > 0) {
2349 #ifdef HAVE_LSTAT
2350 			r = lstat(a->name, &st);
2351 #else
2352 			r = la_stat(a->name, &st);
2353 #endif
2354 			if (r != 0)
2355 				r = errno;
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);
2360 				if (a->fd < 0)
2361 					r = errno;
2362 			}
2363 		}
2364 		return (r);
2365 #endif
2366 	}
2367 	linkname = archive_entry_symlink(a->entry);
2368 	if (linkname != NULL) {
2369 #if HAVE_SYMLINK
2370 		/*
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).
2374 		 */
2375 		if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2376 			unlink(a->name);
2377 		return symlink(linkname, a->name) ? errno : 0;
2378 #else
2379 		return (EPERM);
2380 #endif
2381 	}
2382 
2383 	/*
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!)
2387 	 */
2388 
2389 	/* Mode we want for the final restored object (w/o file type bits). */
2390 	final_mode = a->mode & 07777;
2391 	/*
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.
2395 	 */
2396 	mode = final_mode & 0777 & ~a->user_umask;
2397 
2398 	/*
2399 	 * Always create writable such that [f]setxattr() works if we're not
2400 	 * root.
2401 	 */
2402 	if (a->user_uid != 0 &&
2403 	    a->todo & (TODO_HFS_COMPRESSION | TODO_XATTR)) {
2404 		mode |= 0200;
2405 	}
2406 
2407 	switch (a->mode & AE_IFMT) {
2408 	default:
2409 		/* POSIX requires that we fall through here. */
2410 		/* FALLTHROUGH */
2411 	case AE_IFREG:
2412 		a->tmpname = NULL;
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);
2416 		r = (a->fd < 0);
2417 		break;
2418 	case AE_IFCHR:
2419 #ifdef HAVE_MKNOD
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));
2424 		break;
2425 #else
2426 		/* TODO: Find a better way to warn about our inability
2427 		 * to restore a char device node. */
2428 		return (EINVAL);
2429 #endif /* HAVE_MKNOD */
2430 	case AE_IFBLK:
2431 #ifdef HAVE_MKNOD
2432 		r = mknod(a->name, mode | S_IFBLK,
2433 		    archive_entry_rdev(a->entry));
2434 		break;
2435 #else
2436 		/* TODO: Find a better way to warn about our inability
2437 		 * to restore a block device node. */
2438 		return (EINVAL);
2439 #endif /* HAVE_MKNOD */
2440 	case AE_IFDIR:
2441 		mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2442 		r = mkdir(a->name, mode);
2443 		if (r == 0) {
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;
2454 		}
2455 		break;
2456 	case AE_IFIFO:
2457 #ifdef HAVE_MKFIFO
2458 		r = mkfifo(a->name, mode);
2459 		break;
2460 #else
2461 		/* TODO: Find a better way to warn about our inability
2462 		 * to restore a fifo. */
2463 		return (EINVAL);
2464 #endif /* HAVE_MKFIFO */
2465 	}
2466 
2467 	/* All the system calls above set errno on failure. */
2468 	if (r)
2469 		return (errno);
2470 
2471 	/* If we managed to set the final mode, we've avoided a chmod(). */
2472 	if (mode == final_mode)
2473 		a->todo &= ~TODO_MODE;
2474 	return (0);
2475 }
2476 
2477 /*
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.
2489  *
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
2494  * end-of-archive.
2495  *
2496  * XXX TODO: Directory ACLs should be restored here, for the same
2497  * reason we set directory perms here. XXX
2498  */
2499 static int
2500 _archive_write_disk_close(struct archive *_a)
2501 {
2502 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
2503 	struct fixup_entry *next, *p;
2504 	struct stat st;
2505 	char *c;
2506 	int fd, ret, openflags;
2507 
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);
2512 
2513 	/* Sort dir list so directories are fixed up in depth-first order. */
2514 	p = sort_dir_list(a->fixup_list);
2515 
2516 	while (p != NULL) {
2517 		fd = -1;
2518 		a->pst = NULL; /* Mark stat cache as out-of-date. */
2519 
2520 		/* We must strip trailing slashes from the path to avoid
2521 		   dereferencing symbolic links to directories */
2522 		c = p->name;
2523 		while (*c != '\0')
2524 			c++;
2525 		while (c != p->name && *(c - 1) == '/') {
2526 			c--;
2527 			*c = '\0';
2528 		}
2529 
2530 		if (p->fixup == 0)
2531 			goto skip_fixup_entry;
2532 		else {
2533 			/*
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.
2537 			 */
2538 			openflags = O_BINARY | O_NOFOLLOW | O_RDONLY
2539 			    | O_CLOEXEC;
2540 #if defined(O_DIRECTORY)
2541 			if (p->filetype == AE_IFDIR)
2542 				openflags |= O_DIRECTORY;
2543 #endif
2544 			fd = open(p->name, openflags);
2545 
2546 #if defined(O_DIRECTORY)
2547 			/*
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()
2552 			 */
2553 			if (fd == -1 || p->filetype != AE_IFDIR) {
2554 #if HAVE_FSTAT
2555 				if (fd > 0 && (
2556 				    fstat(fd, &st) != 0 ||
2557 				    la_verify_filetype(st.st_mode,
2558 				    p->filetype) == 0)) {
2559 					goto skip_fixup_entry;
2560 				} else
2561 #endif
2562 				if (lstat(p->name, &st) != 0 ||
2563 				    la_verify_filetype(st.st_mode,
2564 				    p->filetype) == 0) {
2565 					goto skip_fixup_entry;
2566 				}
2567 			}
2568 #else
2569 #if HAVE_FSTAT
2570 			if (fd > 0 && (
2571 			    fstat(fd, &st) != 0 ||
2572 			    la_verify_filetype(st.st_mode,
2573 			    p->filetype) == 0)) {
2574 				goto skip_fixup_entry;
2575 			} else
2576 #endif
2577 			if (lstat(p->name, &st) != 0 ||
2578 			    la_verify_filetype(st.st_mode,
2579 			    p->filetype) == 0) {
2580 				goto skip_fixup_entry;
2581 			}
2582 #endif
2583 		}
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);
2590 		}
2591 		if (p->fixup & TODO_MODE_BASE) {
2592 #ifdef HAVE_FCHMOD
2593 			if (fd >= 0)
2594 				fchmod(fd, p->mode & 07777);
2595 			else
2596 #endif
2597 #ifdef HAVE_LCHMOD
2598 			lchmod(p->name, p->mode & 07777);
2599 #else
2600 			chmod(p->name, p->mode & 07777);
2601 #endif
2602 		}
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);
2612 skip_fixup_entry:
2613 		next = p->next;
2614 		archive_acl_clear(&p->acl);
2615 		free(p->mac_metadata);
2616 		free(p->name);
2617 		if (fd >= 0)
2618 			close(fd);
2619 		free(p);
2620 		p = next;
2621 	}
2622 	a->fixup_list = NULL;
2623 	return (ret);
2624 }
2625 
2626 static int
2627 _archive_write_disk_free(struct archive *_a)
2628 {
2629 	struct archive_write_disk *a;
2630 	int ret;
2631 	if (_a == NULL)
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)) {
2654 		case Z_OK:
2655 			break;
2656 		default:
2657 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2658 			    "Failed to clean up compressor");
2659 			ret = ARCHIVE_FATAL;
2660 			break;
2661 		}
2662 	}
2663 #endif
2664 	free(a);
2665 	return (ret);
2666 }
2667 
2668 /*
2669  * Simple O(n log n) merge sort to order the fixup list.  In
2670  * particular, we want to restore dir timestamps depth-first.
2671  */
2672 static struct fixup_entry *
2673 sort_dir_list(struct fixup_entry *p)
2674 {
2675 	struct fixup_entry *a, *b, *t;
2676 
2677 	if (p == NULL)
2678 		return (NULL);
2679 	/* A one-item list is already sorted. */
2680 	if (p->next == NULL)
2681 		return (p);
2682 
2683 	/* Step 1: split the list. */
2684 	t = p;
2685 	a = p->next->next;
2686 	while (a != NULL) {
2687 		/* Step a twice, t once. */
2688 		a = a->next;
2689 		if (a != NULL)
2690 			a = a->next;
2691 		t = t->next;
2692 	}
2693 	/* Now, t is at the mid-point, so break the list here. */
2694 	b = t->next;
2695 	t->next = NULL;
2696 	a = p;
2697 
2698 	/* Step 2: Recursively sort the two sub-lists. */
2699 	a = sort_dir_list(a);
2700 	b = sort_dir_list(b);
2701 
2702 	/* Step 3: Merge the returned lists. */
2703 	/* Pick the first element for the merged list. */
2704 	if (strcmp(a->name, b->name) > 0) {
2705 		t = p = a;
2706 		a = a->next;
2707 	} else {
2708 		t = p = b;
2709 		b = b->next;
2710 	}
2711 
2712 	/* Always put the later element on the list first. */
2713 	while (a != NULL && b != NULL) {
2714 		if (strcmp(a->name, b->name) > 0) {
2715 			t->next = a;
2716 			a = a->next;
2717 		} else {
2718 			t->next = b;
2719 			b = b->next;
2720 		}
2721 		t = t->next;
2722 	}
2723 
2724 	/* Only one list is non-empty, so just splice it on. */
2725 	if (a != NULL)
2726 		t->next = a;
2727 	if (b != NULL)
2728 		t->next = b;
2729 
2730 	return (p);
2731 }
2732 
2733 /*
2734  * Returns a new, initialized fixup entry.
2735  *
2736  * TODO: Reduce the memory requirements for this list by using a tree
2737  * structure rather than a simple list of names.
2738  */
2739 static struct fixup_entry *
2740 new_fixup(struct archive_write_disk *a, const char *pathname)
2741 {
2742 	struct fixup_entry *fe;
2743 
2744 	fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2745 	if (fe == NULL) {
2746 		archive_set_error(&a->archive, ENOMEM,
2747 		    "Can't allocate memory for a fixup");
2748 		return (NULL);
2749 	}
2750 	fe->next = a->fixup_list;
2751 	a->fixup_list = fe;
2752 	fe->fixup = 0;
2753 	fe->filetype = 0;
2754 	fe->name = strdup(pathname);
2755 	return (fe);
2756 }
2757 
2758 /*
2759  * Returns a fixup structure for the current entry.
2760  */
2761 static struct fixup_entry *
2762 current_fixup(struct archive_write_disk *a, const char *pathname)
2763 {
2764 	if (a->current_fixup == NULL)
2765 		a->current_fixup = new_fixup(a, pathname);
2766 	return (a->current_fixup);
2767 }
2768 
2769 /* Error helper for new *_fsobj functions */
2770 static void
2771 fsobj_error(int *a_eno, struct archive_string *a_estr,
2772     int err, const char *errstr, const char *path)
2773 {
2774 	if (a_eno)
2775 		*a_eno = err;
2776 	if (a_estr)
2777 		archive_string_sprintf(a_estr, "%s%s", errstr, path);
2778 }
2779 
2780 /*
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
2783  * recent paths.
2784  */
2785 /*
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.
2788  */
2789 static int
2790 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2791     int flags, int checking_linkname)
2792 {
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);
2802 #else
2803 	int res = ARCHIVE_OK;
2804 	char *tail;
2805 	char *head;
2806 	int last;
2807 	char c;
2808 	int r;
2809 	struct stat st;
2810 	int chdir_fd;
2811 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2812 	int fd;
2813 #endif
2814 
2815 	/* Nothing to do here if name is empty */
2816 	if(path[0] == '\0')
2817 	    return (ARCHIVE_OK);
2818 
2819 	/*
2820 	 * Guard against symlink tricks.  Reject any archive entry whose
2821 	 * destination would be altered by a symlink.
2822 	 *
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
2827 	 * As we go:
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
2833 	 */
2834 	chdir_fd = la_opendirat(AT_FDCWD, ".");
2835 	__archive_ensure_cloexec_flag(chdir_fd);
2836 	if (chdir_fd < 0) {
2837 		fsobj_error(a_eno, a_estr, errno,
2838 		    "Could not open ", path);
2839 		return (ARCHIVE_FATAL);
2840 	}
2841 	head = path;
2842 	tail = path;
2843 	last = 0;
2844 	/* TODO: reintroduce a safe cache here? */
2845 	/* Skip the root directory if the path is absolute. */
2846 	if(tail == path && tail[0] == '/')
2847 		++tail;
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.
2853 	 */
2854 	while (!last) {
2855 		/*
2856 		 * Skip the separator we just consumed, plus any adjacent ones
2857 		 */
2858 		while (*tail == '/')
2859 		    ++tail;
2860 		/* Skip the next path element. */
2861 		while (*tail != '\0' && *tail != '/')
2862 			++tail;
2863 		/* is this the last path component? */
2864 		last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2865 		/* temporarily truncate the string here */
2866 		c = tail[0];
2867 		tail[0] = '\0';
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);
2871 #else
2872 		r = lstat(head, &st);
2873 #endif
2874 		if (r != 0) {
2875 			tail[0] = c;
2876 			/* We've hit a dir that doesn't exist; stop now. */
2877 			if (errno == ENOENT) {
2878 				break;
2879 			} else {
2880 				/*
2881 				 * Treat any other error as fatal - best to be
2882 				 * paranoid here.
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
2887 				 * sandbox.
2888 				 * TODO: We could do better, but it would
2889 				 * probably require merging the symlink checks
2890 				 * with the deep-directory editing.
2891 				 */
2892 				fsobj_error(a_eno, a_estr, errno,
2893 				    "Could not stat ", path);
2894 				res = ARCHIVE_FAILED;
2895 				break;
2896 			}
2897 		} else if (S_ISDIR(st.st_mode)) {
2898 			if (!last) {
2899 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2900 				fd = la_opendirat(chdir_fd, head);
2901 				if (fd < 0)
2902 					r = -1;
2903 				else {
2904 					r = 0;
2905 					close(chdir_fd);
2906 					chdir_fd = fd;
2907 				}
2908 #else
2909 				r = chdir(head);
2910 #endif
2911 				if (r != 0) {
2912 					tail[0] = c;
2913 					fsobj_error(a_eno, a_estr, errno,
2914 					    "Could not chdir ", path);
2915 					res = (ARCHIVE_FATAL);
2916 					break;
2917 				}
2918 				/* Our view is now from inside this dir: */
2919 				head = tail + 1;
2920 			}
2921 		} else if (S_ISLNK(st.st_mode)) {
2922 			if (last && checking_linkname) {
2923 #ifdef HAVE_LINKAT
2924 				/*
2925 				 * Hardlinks to symlinks are safe to write
2926 				 * if linkat() is supported as it does not
2927 				 * follow symlinks.
2928 				 */
2929 				res = ARCHIVE_OK;
2930 #else
2931 				/*
2932 				 * We return ARCHIVE_FAILED here as we are
2933 				 * not able to safely write hardlinks
2934 				 * to symlinks.
2935 				 */
2936 				tail[0] = c;
2937 				fsobj_error(a_eno, a_estr, errno,
2938 				    "Cannot write hardlink to symlink ",
2939 				    path);
2940 				res = ARCHIVE_FAILED;
2941 #endif
2942 				break;
2943 			} else
2944 			if (last) {
2945 				/*
2946 				 * Last element is symlink; remove it
2947 				 * so we can overwrite it with the
2948 				 * item being extracted.
2949 				 */
2950 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2951 				r = unlinkat(chdir_fd, head, 0);
2952 #else
2953 				r = unlink(head);
2954 #endif
2955 				if (r != 0) {
2956 					tail[0] = c;
2957 					fsobj_error(a_eno, a_estr, errno,
2958 					    "Could not remove symlink ",
2959 					    path);
2960 					res = ARCHIVE_FAILED;
2961 					break;
2962 				}
2963 				/*
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.
2968 				 */
2969 				tail[0] = c;
2970 				/*
2971 				 * FIXME:  not sure how important this is to
2972 				 * restore
2973 				 */
2974 				/*
2975 				if (!S_ISLNK(path)) {
2976 					fsobj_error(a_eno, a_estr, 0,
2977 					    "Removing symlink ", path);
2978 				}
2979 				*/
2980 				/* Symlink gone.  No more problem! */
2981 				res = ARCHIVE_OK;
2982 				break;
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);
2987 #else
2988 				r = unlink(head);
2989 #endif
2990 				if (r != 0) {
2991 					tail[0] = c;
2992 					fsobj_error(a_eno, a_estr, 0,
2993 					    "Cannot remove intervening "
2994 					    "symlink ", path);
2995 					res = ARCHIVE_FAILED;
2996 					break;
2997 				}
2998 				tail[0] = c;
2999 			} else if ((flags &
3000 			    ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
3001 				/*
3002 				 * We are not the last element and we want to
3003 				 * follow symlinks if they are a directory.
3004 				 *
3005 				 * This is needed to extract hardlinks over
3006 				 * symlinks.
3007 				 */
3008 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3009 				r = fstatat(chdir_fd, head, &st, 0);
3010 #else
3011 				r = la_stat(head, &st);
3012 #endif
3013 				if (r != 0) {
3014 					tail[0] = c;
3015 					if (errno == ENOENT) {
3016 						break;
3017 					} else {
3018 						fsobj_error(a_eno, a_estr,
3019 						    errno,
3020 						    "Could not stat ", path);
3021 						res = (ARCHIVE_FAILED);
3022 						break;
3023 					}
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);
3027 					if (fd < 0)
3028 						r = -1;
3029 					else {
3030 						r = 0;
3031 						close(chdir_fd);
3032 						chdir_fd = fd;
3033 					}
3034 #else
3035 					r = chdir(head);
3036 #endif
3037 					if (r != 0) {
3038 						tail[0] = c;
3039 						fsobj_error(a_eno, a_estr,
3040 						    errno,
3041 						    "Could not chdir ", path);
3042 						res = (ARCHIVE_FATAL);
3043 						break;
3044 					}
3045 					/*
3046 					 * Our view is now from inside
3047 					 * this dir:
3048 					 */
3049 					head = tail + 1;
3050 				} else {
3051 					tail[0] = c;
3052 					fsobj_error(a_eno, a_estr, 0,
3053 					    "Cannot extract through "
3054 					    "symlink ", path);
3055 					res = ARCHIVE_FAILED;
3056 					break;
3057 				}
3058 			} else {
3059 				tail[0] = c;
3060 				fsobj_error(a_eno, a_estr, 0,
3061 				    "Cannot extract through symlink ", path);
3062 				res = ARCHIVE_FAILED;
3063 				break;
3064 			}
3065 		}
3066 		/* be sure to always maintain this */
3067 		tail[0] = c;
3068 		if (tail[0] != '\0')
3069 			tail++; /* Advance to the next segment. */
3070 	}
3071 	/* Catches loop exits via break */
3072 	tail[0] = c;
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 */
3076 	if (chdir_fd >= 0)
3077 		close(chdir_fd);
3078 #elif HAVE_FCHDIR
3079 	/* If we changed directory above, restore it here. */
3080 	if (chdir_fd >= 0) {
3081 		r = fchdir(chdir_fd);
3082 		if (r != 0) {
3083 			fsobj_error(a_eno, a_estr, errno,
3084 			    "chdir() failure", "");
3085 		}
3086 		close(chdir_fd);
3087 		chdir_fd = -1;
3088 		if (r != 0) {
3089 			res = (ARCHIVE_FATAL);
3090 		}
3091 	}
3092 #endif
3093 	/* TODO: reintroduce a safe cache here? */
3094 	return res;
3095 #endif
3096 }
3097 
3098 /*
3099  * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
3100  * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
3101  */
3102 static int
3103 check_symlinks(struct archive_write_disk *a)
3104 {
3105 	struct archive_string error_string;
3106 	int error_number;
3107 	int rc;
3108 	archive_string_init(&error_string);
3109 	rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
3110 	    a->flags, 0);
3111 	if (rc != ARCHIVE_OK) {
3112 		archive_set_error(&a->archive, error_number, "%s",
3113 		    error_string.s);
3114 	}
3115 	archive_string_free(&error_string);
3116 	a->pst = NULL;	/* to be safe */
3117 	return rc;
3118 }
3119 
3120 
3121 #if defined(__CYGWIN__)
3122 /*
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
3129  */
3130 static void
3131 cleanup_pathname_win(char *path)
3132 {
3133 	wchar_t wc;
3134 	char *p;
3135 	size_t alen, l;
3136 	int mb, complete, utf8;
3137 
3138 	alen = 0;
3139 	mb = 0;
3140 	complete = 1;
3141 	utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
3142 	for (p = path; *p != '\0'; p++) {
3143 		++alen;
3144 		if (*p == '\\') {
3145 			/* If previous byte is smaller than 128,
3146 			 * this is not second byte of multibyte characters,
3147 			 * so we can replace '\' with '/'. */
3148 			if (utf8 || !mb)
3149 				*p = '/';
3150 			else
3151 				complete = 0;/* uncompleted. */
3152 		} else if (*(unsigned char *)p > 127)
3153 			mb = 1;
3154 		else
3155 			mb = 0;
3156 		/* Rewrite the path name if its next character is unusable. */
3157 		if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
3158 		    *p == '<' || *p == '>' || *p == '|')
3159 			*p = '_';
3160 	}
3161 	if (complete)
3162 		return;
3163 
3164 	/*
3165 	 * Convert path separator in wide-character.
3166 	 */
3167 	p = path;
3168 	while (*p != '\0' && alen) {
3169 		l = mbtowc(&wc, p, alen);
3170 		if (l == (size_t)-1) {
3171 			while (*p != '\0') {
3172 				if (*p == '\\')
3173 					*p = '/';
3174 				++p;
3175 			}
3176 			break;
3177 		}
3178 		if (l == 1 && wc == L'\\')
3179 			*p = '/';
3180 		p += l;
3181 		alen -= l;
3182 	}
3183 }
3184 #endif
3185 
3186 /*
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.
3192  */
3193 static int
3194 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
3195     int flags)
3196 {
3197 	char *dest, *src;
3198 	char separator = '\0';
3199 
3200 	dest = src = path;
3201 	if (*src == '\0') {
3202 		fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3203 		    "Invalid empty ", "pathname");
3204 		return (ARCHIVE_FAILED);
3205 	}
3206 
3207 #if defined(__CYGWIN__)
3208 	cleanup_pathname_win(path);
3209 #endif
3210 	/* Skip leading '/'. */
3211 	if (*src == '/') {
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);
3216 		}
3217 
3218 		separator = *src++;
3219 	}
3220 
3221 	/* Scan the pathname one element at a time. */
3222 	for (;;) {
3223 		/* src points to first char after '/' */
3224 		if (src[0] == '\0') {
3225 			break;
3226 		} else if (src[0] == '/') {
3227 			/* Found '//', ignore second one. */
3228 			src++;
3229 			continue;
3230 		} else if (src[0] == '.') {
3231 			if (src[1] == '\0') {
3232 				/* Ignore trailing '.' */
3233 				break;
3234 			} else if (src[1] == '/') {
3235 				/* Skip './'. */
3236 				src += 2;
3237 				continue;
3238 			} else if (src[1] == '.') {
3239 				if (src[2] == '/' || src[2] == '\0') {
3240 					/* Conditionally warn about '..' */
3241 					if (flags
3242 					    & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3243 						fsobj_error(a_eno, a_estr,
3244 						    ARCHIVE_ERRNO_MISC,
3245 						    "Path contains ", "'..'");
3246 						return (ARCHIVE_FAILED);
3247 					}
3248 				}
3249 				/*
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.
3255 				 */
3256 			}
3257 		}
3258 
3259 		/* Copy current element, including leading '/'. */
3260 		if (separator)
3261 			*dest++ = '/';
3262 		while (*src != '\0' && *src != '/') {
3263 			*dest++ = *src++;
3264 		}
3265 
3266 		if (*src == '\0')
3267 			break;
3268 
3269 		/* Skip '/' separator. */
3270 		separator = *src++;
3271 	}
3272 	/*
3273 	 * We've just copied zero or more path elements, not including the
3274 	 * final '/'.
3275 	 */
3276 	if (dest == path) {
3277 		/*
3278 		 * Nothing got copied.  The path must have been something
3279 		 * like '.' or '/' or './' or '/././././/./'.
3280 		 */
3281 		if (separator)
3282 			*dest++ = '/';
3283 		else
3284 			*dest++ = '.';
3285 	}
3286 	/* Terminate the result. */
3287 	*dest = '\0';
3288 	return (ARCHIVE_OK);
3289 }
3290 
3291 static int
3292 cleanup_pathname(struct archive_write_disk *a)
3293 {
3294 	struct archive_string error_string;
3295 	int error_number;
3296 	int rc;
3297 	archive_string_init(&error_string);
3298 	rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3299 	    a->flags);
3300 	if (rc != ARCHIVE_OK) {
3301 		archive_set_error(&a->archive, error_number, "%s",
3302 		    error_string.s);
3303 	}
3304 	archive_string_free(&error_string);
3305 	return rc;
3306 }
3307 
3308 /*
3309  * Create the parent directory of the specified path, assuming path
3310  * is already in mutable storage.
3311  */
3312 static int
3313 create_parent_dir(struct archive_write_disk *a, char *path)
3314 {
3315 	char *slash;
3316 	int r;
3317 
3318 	/* Remove tail element to obtain parent name. */
3319 	slash = strrchr(path, '/');
3320 	if (slash == NULL)
3321 		return (ARCHIVE_OK);
3322 	*slash = '\0';
3323 	r = create_dir(a, path);
3324 	*slash = '/';
3325 	return (r);
3326 }
3327 
3328 /*
3329  * Create the specified dir, recursing to create parents as necessary.
3330  *
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.
3334  */
3335 static int
3336 create_dir(struct archive_write_disk *a, char *path)
3337 {
3338 	struct stat st;
3339 	struct fixup_entry *le;
3340 	char *slash, *base;
3341 	mode_t mode_final, mode;
3342 	int r;
3343 
3344 	/* Check for special names and just skip them. */
3345 	slash = strrchr(path, '/');
3346 	if (slash == NULL)
3347 		base = path;
3348 	else
3349 		base = slash + 1;
3350 
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) {
3356 			*slash = '\0';
3357 			r = create_dir(a, path);
3358 			*slash = '/';
3359 			return (r);
3360 		}
3361 		return (ARCHIVE_OK);
3362 	}
3363 
3364 	/*
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.
3368 	 */
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);
3376 		}
3377 		if (unlink(path) != 0) {
3378 			archive_set_error(&a->archive, errno,
3379 			    "Can't create directory '%s': "
3380 			    "Conflicting file cannot be removed",
3381 			    path);
3382 			return (ARCHIVE_FAILED);
3383 		}
3384 	} else if (errno != ENOENT && errno != ENOTDIR) {
3385 		/* Stat failed? */
3386 		archive_set_error(&a->archive, errno,
3387 		    "Can't test directory '%s'", path);
3388 		return (ARCHIVE_FAILED);
3389 	} else if (slash != NULL) {
3390 		*slash = '\0';
3391 		r = create_dir(a, path);
3392 		*slash = '/';
3393 		if (r != ARCHIVE_OK)
3394 			return (r);
3395 	}
3396 
3397 	/*
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.
3404 	 */
3405 	mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3406 	/* Mode we want on disk during the restore process. */
3407 	mode = mode_final;
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);
3413 			if (le == NULL)
3414 				return (ARCHIVE_FATAL);
3415 			le->fixup |=TODO_MODE_BASE;
3416 			le->mode = mode_final;
3417 		}
3418 		return (ARCHIVE_OK);
3419 	}
3420 
3421 	/*
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
3425 	 * added.
3426 	 */
3427 	if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3428 		return (ARCHIVE_OK);
3429 
3430 	archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3431 	    path);
3432 	return (ARCHIVE_FAILED);
3433 }
3434 
3435 /*
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.
3444  */
3445 static int
3446 set_ownership(struct archive_write_disk *a)
3447 {
3448 #if !defined(__CYGWIN__) && !defined(__linux__)
3449 /*
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.
3454  */
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);
3459 	}
3460 #endif
3461 
3462 #ifdef HAVE_FCHOWN
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);
3468 	}
3469 #endif
3470 
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. */
3473 #ifdef HAVE_LCHOWN
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);
3478 	}
3479 #elif HAVE_CHOWN
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);
3484 	}
3485 #endif
3486 
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);
3491 }
3492 
3493 /*
3494  * Note: Returns 0 on success, non-zero on failure.
3495  */
3496 static int
3497 set_time(int fd, int mode, const char *name,
3498     time_t atime, long atime_nsec,
3499     time_t mtime, long mtime_nsec)
3500 {
3501 	/* Select the best implementation for this platform. */
3502 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3503 	/*
3504 	 * utimensat() and futimens() are defined in
3505 	 * POSIX.1-2008. They support ns resolution and setting times
3506 	 * on fds and symlinks.
3507 	 */
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;
3514 	if (fd >= 0)
3515 		return futimens(fd, ts);
3516 	return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3517 
3518 #elif HAVE_UTIMES
3519 	/*
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
3523 	 * in POSIX.
3524 	 */
3525 	struct timeval times[2];
3526 
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;
3531 
3532 #ifdef HAVE_FUTIMES
3533 	if (fd >= 0)
3534 		return (futimes(fd, times));
3535 #else
3536 	(void)fd; /* UNUSED */
3537 #endif
3538 #ifdef HAVE_LUTIMES
3539 	(void)mode; /* UNUSED */
3540 	return (lutimes(name, times));
3541 #else
3542 	if (S_ISLNK(mode))
3543 		return (0);
3544 	return (utimes(name, times));
3545 #endif
3546 
3547 #elif defined(HAVE_UTIME)
3548 	/*
3549 	 * utime() is POSIX-standard but only supports 1s resolution and
3550 	 * does not support fds or symlinks.
3551 	 */
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;
3559 	if (S_ISLNK(mode))
3560 		return (ARCHIVE_OK);
3561 	return (utime(name, &times));
3562 
3563 #else
3564 	/*
3565 	 * We don't know how to set the time on this platform.
3566 	 */
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);
3573 #endif
3574 }
3575 
3576 #ifdef F_SETTIMES
3577 static int
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)
3582 {
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;
3591 #else
3592 	tstamp.atime.tv_usec = atime_nsec / 1000;
3593 	tstamp.mtime.tv_usec = mtime_nsec / 1000;
3594 	tstamp.ctime.tv_usec = ctime_nsec / 1000;
3595 #endif
3596 	return (fcntl(fd,F_SETTIMES,&tstamp));
3597 }
3598 #endif /* F_SETTIMES */
3599 
3600 static int
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)
3607 {
3608 	/* Note: set_time doesn't use libarchive return conventions!
3609 	 * It uses syscall conventions.  So 0 here instead of ARCHIVE_OK. */
3610 	int r1 = 0, r2 = 0;
3611 
3612 #ifdef F_SETTIMES
3613 	 /*
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
3617 	 */
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);
3623 	}
3624 #else /* Tru64 */
3625 	(void)cctime; /* UNUSED */
3626 	(void)ctime_nanos; /* UNUSED */
3627 #endif /* Tru64 */
3628 
3629 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3630 	/*
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.
3637 	 */
3638 	if (birthtime < mtime
3639 	    || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3640 		r1 = set_time(fd, mode, name,
3641 			      atime, atime_nanos,
3642 			      birthtime, birthtime_nanos);
3643 #else
3644 	(void)birthtime; /* UNUSED */
3645 	(void)birthtime_nanos; /* UNUSED */
3646 #endif
3647 	r2 = set_time(fd, mode, name,
3648 		      atime, atime_nanos,
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);
3654 	}
3655 	return (ARCHIVE_OK);
3656 }
3657 
3658 static int
3659 set_times_from_entry(struct archive_write_disk *a)
3660 {
3661 	time_t atime, birthtime, mtime, cctime;
3662 	long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3663 
3664 	/* Suitable defaults. */
3665 	atime = birthtime = mtime = cctime = a->start_time;
3666 	atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3667 
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)
3672 #endif
3673 	    && !archive_entry_mtime_is_set(a->entry))
3674 		return (ARCHIVE_OK);
3675 
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);
3679 	}
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);
3683 	}
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);
3687 	}
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);
3691 	}
3692 
3693 	return set_times(a, a->fd, a->mode, a->name,
3694 			 atime, atime_nsec,
3695 			 birthtime, birthtime_nsec,
3696 			 mtime, mtime_nsec,
3697 			 cctime, ctime_nsec);
3698 }
3699 
3700 static int
3701 set_mode(struct archive_write_disk *a, int mode)
3702 {
3703 	int r = ARCHIVE_OK;
3704 	int r2;
3705 	mode &= 07777; /* Strip off file type bits. */
3706 
3707 	if (a->todo & TODO_SGID_CHECK) {
3708 		/*
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.
3713 		 */
3714 		if ((r = lazy_stat(a)) != ARCHIVE_OK)
3715 			return (r);
3716 		if (a->pst->st_gid != a->gid) {
3717 			mode &= ~ S_ISGID;
3718 			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3719 				/*
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.
3725 				 */
3726 				archive_set_error(&a->archive, -1,
3727 				    "Can't restore SGID bit");
3728 				r = ARCHIVE_WARN;
3729 			}
3730 		}
3731 		/* While we're here, double-check the UID. */
3732 		if (a->pst->st_uid != a->uid
3733 		    && (a->todo & TODO_SUID)) {
3734 			mode &= ~ S_ISUID;
3735 			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3736 				archive_set_error(&a->archive, -1,
3737 				    "Can't restore SUID bit");
3738 				r = ARCHIVE_WARN;
3739 			}
3740 		}
3741 		a->todo &= ~TODO_SGID_CHECK;
3742 		a->todo &= ~TODO_SUID_CHECK;
3743 	} else if (a->todo & TODO_SUID_CHECK) {
3744 		/*
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
3747 		 * the process UID.
3748 		 */
3749 		if (a->user_uid != a->uid) {
3750 			mode &= ~ S_ISUID;
3751 			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3752 				archive_set_error(&a->archive, -1,
3753 				    "Can't make file SUID");
3754 				r = ARCHIVE_WARN;
3755 			}
3756 		}
3757 		a->todo &= ~TODO_SUID_CHECK;
3758 	}
3759 
3760 	if (S_ISLNK(a->mode)) {
3761 #ifdef HAVE_LCHMOD
3762 		/*
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
3768 		 * impact.
3769 		 */
3770 		if (lchmod(a->name, mode) != 0) {
3771 			switch (errno) {
3772 			case ENOTSUP:
3773 			case ENOSYS:
3774 #if ENOTSUP != EOPNOTSUPP
3775 			case EOPNOTSUPP:
3776 #endif
3777 				/*
3778 				 * if lchmod is defined but the platform
3779 				 * doesn't support it, silently ignore
3780 				 * error
3781 				 */
3782 				break;
3783 			default:
3784 				archive_set_error(&a->archive, errno,
3785 				    "Can't set permissions to 0%o", (int)mode);
3786 				r = ARCHIVE_WARN;
3787 			}
3788 		}
3789 #endif
3790 	} else if (!S_ISDIR(a->mode)) {
3791 		/*
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.
3796 		 */
3797 #ifdef HAVE_FCHMOD
3798 		if (a->fd >= 0)
3799 			r2 = fchmod(a->fd, mode);
3800 		else
3801 #endif
3802 		/* If this platform lacks fchmod(), then
3803 		 * we'll just use chmod(). */
3804 		r2 = chmod(a->name, mode);
3805 
3806 		if (r2 != 0) {
3807 			archive_set_error(&a->archive, errno,
3808 			    "Can't set permissions to 0%o", (int)mode);
3809 			r = ARCHIVE_WARN;
3810 		}
3811 	}
3812 	return (r);
3813 }
3814 
3815 static int
3816 set_fflags(struct archive_write_disk *a)
3817 {
3818 	struct fixup_entry *le;
3819 	unsigned long	set, clear;
3820 	int		r;
3821 	mode_t		mode = archive_entry_mode(a->entry);
3822 	/*
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.
3829 	 *
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
3835 	 * being restored.
3836 	 */
3837 	const int	critical_flags = 0
3838 #ifdef SF_IMMUTABLE
3839 	    | SF_IMMUTABLE
3840 #endif
3841 #ifdef UF_IMMUTABLE
3842 	    | UF_IMMUTABLE
3843 #endif
3844 #ifdef SF_APPEND
3845 	    | SF_APPEND
3846 #endif
3847 #ifdef UF_APPEND
3848 	    | UF_APPEND
3849 #endif
3850 #if defined(FS_APPEND_FL)
3851 	    | FS_APPEND_FL
3852 #elif defined(EXT2_APPEND_FL)
3853 	    | EXT2_APPEND_FL
3854 #endif
3855 #if defined(FS_IMMUTABLE_FL)
3856 	    | FS_IMMUTABLE_FL
3857 #elif defined(EXT2_IMMUTABLE_FL)
3858 	    | EXT2_IMMUTABLE_FL
3859 #endif
3860 #ifdef FS_JOURNAL_DATA_FL
3861 	    | FS_JOURNAL_DATA_FL
3862 #endif
3863 	;
3864 
3865 	if (a->todo & TODO_FFLAGS) {
3866 		archive_entry_fflags(a->entry, &set, &clear);
3867 
3868 		/*
3869 		 * The first test encourages the compiler to eliminate
3870 		 * all of this if it's not necessary.
3871 		 */
3872 		if ((critical_flags != 0)  &&  (set & critical_flags)) {
3873 			le = current_fixup(a, a->name);
3874 			if (le == NULL)
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)
3881 				le->mode = mode;
3882 		} else {
3883 			r = set_fflags_platform(a, a->fd,
3884 			    a->name, mode, set, clear);
3885 			if (r != ARCHIVE_OK)
3886 				return (r);
3887 		}
3888 	}
3889 	return (ARCHIVE_OK);
3890 }
3891 
3892 static int
3893 clear_nochange_fflags(struct archive_write_disk *a)
3894 {
3895 	mode_t		mode = archive_entry_mode(a->entry);
3896 	const int nochange_flags = 0
3897 #ifdef SF_IMMUTABLE
3898 	    | SF_IMMUTABLE
3899 #endif
3900 #ifdef UF_IMMUTABLE
3901 	    | UF_IMMUTABLE
3902 #endif
3903 #ifdef SF_APPEND
3904 	    | SF_APPEND
3905 #endif
3906 #ifdef UF_APPEND
3907 	    | UF_APPEND
3908 #endif
3909 #ifdef EXT2_APPEND_FL
3910 	    | EXT2_APPEND_FL
3911 #endif
3912 #ifdef EXT2_IMMUTABLE_FL
3913 	    | EXT2_IMMUTABLE_FL
3914 #endif
3915 	;
3916 
3917 	return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3918 	    nochange_flags));
3919 }
3920 
3921 
3922 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3923 /*
3924  * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3925  */
3926 static int
3927 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3928     mode_t mode, unsigned long set, unsigned long clear)
3929 {
3930 	int r;
3931 	const int sf_mask = 0
3932 #ifdef SF_APPEND
3933 	    | SF_APPEND
3934 #endif
3935 #ifdef SF_ARCHIVED
3936 	    | SF_ARCHIVED
3937 #endif
3938 #ifdef SF_IMMUTABLE
3939 	    | SF_IMMUTABLE
3940 #endif
3941 #ifdef SF_NOUNLINK
3942 	    | SF_NOUNLINK
3943 #endif
3944 	;
3945 	(void)mode; /* UNUSED */
3946 
3947 	if (set == 0  && clear == 0)
3948 		return (ARCHIVE_OK);
3949 
3950 	/*
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
3955 	 */
3956 	if ((r = lazy_stat(a)) != ARCHIVE_OK)
3957 		return (r);
3958 
3959 	a->st.st_flags &= ~clear;
3960 	a->st.st_flags |= set;
3961 
3962 	/* Only super-user may change SF_* flags */
3963 
3964 	if (a->user_uid != 0)
3965 		a->st.st_flags &= ~sf_mask;
3966 
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);
3971 #endif
3972 	/*
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.
3976 	 */
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);
3985 	}
3986 	if (chflags(name, a->st.st_flags) == 0)
3987 		return (ARCHIVE_OK);
3988 #endif
3989 	archive_set_error(&a->archive, errno,
3990 	    "Failed to set file flags");
3991 	return (ARCHIVE_WARN);
3992 }
3993 
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))
3998 /*
3999  * Linux uses ioctl() to read and write file flags.
4000  */
4001 static int
4002 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4003     mode_t mode, unsigned long set, unsigned long clear)
4004 {
4005 	int		 ret;
4006 	int		 myfd = fd;
4007 	int newflags, oldflags;
4008 	/*
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.
4014 	 */
4015 	const int sf_mask = 0
4016 #if defined(FS_IMMUTABLE_FL)
4017 	    | FS_IMMUTABLE_FL
4018 #elif defined(EXT2_IMMUTABLE_FL)
4019 	    | EXT2_IMMUTABLE_FL
4020 #endif
4021 #if defined(FS_APPEND_FL)
4022 	    | FS_APPEND_FL
4023 #elif defined(EXT2_APPEND_FL)
4024 	    | EXT2_APPEND_FL
4025 #endif
4026 #if defined(FS_JOURNAL_DATA_FL)
4027 	    | FS_JOURNAL_DATA_FL
4028 #endif
4029 	;
4030 
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);
4036 
4037 	/* If we weren't given an fd, open it ourselves. */
4038 	if (myfd < 0) {
4039 		myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY |
4040 		    O_CLOEXEC | O_NOFOLLOW);
4041 		__archive_ensure_cloexec_flag(myfd);
4042 	}
4043 	if (myfd < 0)
4044 		return (ARCHIVE_OK);
4045 
4046 	/*
4047 	 * XXX As above, this would be way simpler if we didn't have
4048 	 * to read the current flags from disk. XXX
4049 	 */
4050 	ret = ARCHIVE_OK;
4051 
4052 	/* Read the current file flags. */
4053 	if (ioctl(myfd,
4054 #ifdef FS_IOC_GETFLAGS
4055 	    FS_IOC_GETFLAGS,
4056 #else
4057 	    EXT2_IOC_GETFLAGS,
4058 #endif
4059 	    &oldflags) < 0)
4060 		goto fail;
4061 
4062 	/* Try setting the flags as given. */
4063 	newflags = (oldflags & ~clear) | set;
4064 	if (ioctl(myfd,
4065 #ifdef FS_IOC_SETFLAGS
4066 	    FS_IOC_SETFLAGS,
4067 #else
4068 	    EXT2_IOC_SETFLAGS,
4069 #endif
4070 	    &newflags) >= 0)
4071 		goto cleanup;
4072 	if (errno != EPERM)
4073 		goto fail;
4074 
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;
4079 	if (ioctl(myfd,
4080 #ifdef FS_IOC_SETFLAGS
4081 	    FS_IOC_SETFLAGS,
4082 #else
4083 	    EXT2_IOC_SETFLAGS,
4084 #endif
4085 	    &newflags) >= 0)
4086 		goto cleanup;
4087 
4088 	/* We couldn't set the flags, so report the failure. */
4089 fail:
4090 	archive_set_error(&a->archive, errno,
4091 	    "Failed to set file flags");
4092 	ret = ARCHIVE_WARN;
4093 cleanup:
4094 	if (fd < 0)
4095 		close(myfd);
4096 	return (ret);
4097 }
4098 
4099 #else
4100 
4101 /*
4102  * Of course, some systems have neither BSD chflags() nor Linux' flags
4103  * support through ioctl().
4104  */
4105 static int
4106 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4107     mode_t mode, unsigned long set, unsigned long clear)
4108 {
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);
4116 }
4117 
4118 #endif /* __linux */
4119 
4120 #ifndef HAVE_COPYFILE_H
4121 /* Default is to simply drop Mac extended metadata. */
4122 static int
4123 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4124 		 const void *metadata, size_t metadata_size)
4125 {
4126 	(void)a; /* UNUSED */
4127 	(void)pathname; /* UNUSED */
4128 	(void)metadata; /* UNUSED */
4129 	(void)metadata_size; /* UNUSED */
4130 	return (ARCHIVE_OK);
4131 }
4132 
4133 static int
4134 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4135 {
4136 	(void)a; /* UNUSED */
4137 	(void)pathname; /* UNUSED */
4138 	return (ARCHIVE_OK);
4139 }
4140 #else
4141 
4142 /*
4143  * On Mac OS, we use copyfile() to unpack the metadata and
4144  * apply it to the target file.
4145  */
4146 
4147 #if defined(HAVE_SYS_XATTR_H)
4148 static int
4149 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
4150 {
4151 	ssize_t xattr_size;
4152 	char *xattr_names = NULL, *xattr_val = NULL;
4153 	int ret = ARCHIVE_OK, xattr_i;
4154 
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)");
4159 		ret = ARCHIVE_WARN;
4160 		goto exit_xattr;
4161 	}
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;
4167 		goto exit_xattr;
4168 	}
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)");
4173 		ret = ARCHIVE_WARN;
4174 		goto exit_xattr;
4175 	}
4176 	for (xattr_i = 0; xattr_i < xattr_size;
4177 	    xattr_i += strlen(xattr_names + xattr_i) + 1) {
4178 		char *xattr_val_saved;
4179 		ssize_t s;
4180 		int f;
4181 
4182 		s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
4183 		if (s == -1) {
4184 			archive_set_error(&a->archive, errno,
4185 			    "Failed to get metadata(xattr)");
4186 			ret = ARCHIVE_WARN;
4187 			goto exit_xattr;
4188 		}
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)");
4194 			ret = ARCHIVE_WARN;
4195 			free(xattr_val_saved);
4196 			goto exit_xattr;
4197 		}
4198 		s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4199 		if (s == -1) {
4200 			archive_set_error(&a->archive, errno,
4201 			    "Failed to get metadata(xattr)");
4202 			ret = ARCHIVE_WARN;
4203 			goto exit_xattr;
4204 		}
4205 		f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4206 		if (f == -1) {
4207 			archive_set_error(&a->archive, errno,
4208 			    "Failed to get metadata(xattr)");
4209 			ret = ARCHIVE_WARN;
4210 			goto exit_xattr;
4211 		}
4212 	}
4213 exit_xattr:
4214 	free(xattr_names);
4215 	free(xattr_val);
4216 	return (ret);
4217 }
4218 #endif
4219 
4220 static int
4221 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
4222 {
4223 #ifndef HAVE_SYS_ACL_H
4224 	return 0;
4225 #else
4226 	acl_t acl, dfacl = NULL;
4227 	int acl_r, ret = ARCHIVE_OK;
4228 
4229 	acl = acl_get_fd(tmpfd);
4230 	if (acl == NULL) {
4231 		if (errno == ENOENT)
4232 			/* There are not any ACLs. */
4233 			return (ret);
4234 		archive_set_error(&a->archive, errno,
4235 		    "Failed to get metadata(acl)");
4236 		ret = ARCHIVE_WARN;
4237 		goto exit_acl;
4238 	}
4239 	dfacl = acl_dup(acl);
4240 	acl_r = acl_set_fd(dffd, dfacl);
4241 	if (acl_r == -1) {
4242 		archive_set_error(&a->archive, errno,
4243 		    "Failed to get metadata(acl)");
4244 		ret = ARCHIVE_WARN;
4245 		goto exit_acl;
4246 	}
4247 exit_acl:
4248 	if (acl)
4249 		acl_free(acl);
4250 	if (dfacl)
4251 		acl_free(dfacl);
4252 	return (ret);
4253 #endif
4254 }
4255 
4256 static int
4257 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4258 {
4259 	struct archive_string tmpdatafork;
4260 	int tmpfd;
4261 
4262 	archive_string_init(&tmpdatafork);
4263 	archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
4264 	tmpfd = mkstemp(tmpdatafork.s);
4265 	if (tmpfd < 0) {
4266 		archive_set_error(&a->archive, errno,
4267 		    "Failed to mkstemp");
4268 		archive_string_free(&tmpdatafork);
4269 		return (-1);
4270 	}
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");
4276 		close(tmpfd);
4277 		tmpfd = -1;
4278 	}
4279 	unlink(tmpdatafork.s);
4280 	archive_string_free(&tmpdatafork);
4281 	return (tmpfd);
4282 }
4283 
4284 static int
4285 copy_metadata(struct archive_write_disk *a, const char *metadata,
4286     const char *datafork, int datafork_compressed)
4287 {
4288 	int ret = ARCHIVE_OK;
4289 
4290 	if (datafork_compressed) {
4291 		int dffd, tmpfd;
4292 
4293 		tmpfd = create_tempdatafork(a, metadata);
4294 		if (tmpfd == -1)
4295 			return (ARCHIVE_WARN);
4296 
4297 		/*
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.
4301 		 */
4302 		dffd = open(datafork, 0);
4303 		if (dffd == -1) {
4304 			archive_set_error(&a->archive, errno,
4305 			    "Failed to open the data fork for metadata");
4306 			close(tmpfd);
4307 			return (ARCHIVE_WARN);
4308 		}
4309 
4310 #if defined(HAVE_SYS_XATTR_H)
4311 		ret = copy_xattrs(a, tmpfd, dffd);
4312 		if (ret == ARCHIVE_OK)
4313 #endif
4314 			ret = copy_acls(a, tmpfd, dffd);
4315 		close(tmpfd);
4316 		close(dffd);
4317 	} else {
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");
4323 			ret = ARCHIVE_WARN;
4324 		}
4325 	}
4326 	return (ret);
4327 }
4328 
4329 static int
4330 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4331 		 const void *metadata, size_t metadata_size)
4332 {
4333 	struct archive_string tmp;
4334 	ssize_t written;
4335 	int fd;
4336 	int ret = ARCHIVE_OK;
4337 
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);
4346 
4347 	if (fd < 0) {
4348 		archive_set_error(&a->archive, errno,
4349 				  "Failed to restore metadata");
4350 		archive_string_free(&tmp);
4351 		return (ARCHIVE_WARN);
4352 	}
4353 	written = write(fd, metadata, metadata_size);
4354 	close(fd);
4355 	if ((size_t)written != metadata_size) {
4356 		archive_set_error(&a->archive, errno,
4357 				  "Failed to restore metadata");
4358 		ret = ARCHIVE_WARN;
4359 	} else {
4360 		int compressed;
4361 
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;
4366 		else
4367 #endif
4368 			compressed = 0;
4369 		ret = copy_metadata(a, tmp.s, pathname, compressed);
4370 	}
4371 	unlink(tmp.s);
4372 	archive_string_free(&tmp);
4373 	return (ret);
4374 }
4375 
4376 static int
4377 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4378 {
4379 	char buff[8];
4380 	struct stat st;
4381 	const char *p;
4382 	struct archive_string datafork;
4383 	int fd = -1, ret = ARCHIVE_OK;
4384 
4385 	archive_string_init(&datafork);
4386 	/* Check if the current file name is a type of the resource
4387 	 * fork file. */
4388 	p = strrchr(pathname, '/');
4389 	if (p == NULL)
4390 		p = pathname;
4391 	else
4392 		p++;
4393 	if (p[0] != '.' || p[1] != '_')
4394 		goto skip_appledouble;
4395 
4396 	/*
4397 	 * Check if the data fork file exists.
4398 	 *
4399 	 * TODO: Check if this write disk object has handled it.
4400 	 */
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;
4406 
4407 	/*
4408 	 * Check if the file is in the AppleDouble form.
4409 	 */
4410 	fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4411 	__archive_ensure_cloexec_flag(fd);
4412 	if (fd == -1) {
4413 		archive_set_error(&a->archive, errno,
4414 		    "Failed to open a restoring file");
4415 		ret = ARCHIVE_WARN;
4416 		goto skip_appledouble;
4417 	}
4418 	if (read(fd, buff, 8) == -1) {
4419 		archive_set_error(&a->archive, errno,
4420 		    "Failed to read a restoring file");
4421 		close(fd);
4422 		ret = ARCHIVE_WARN;
4423 		goto skip_appledouble;
4424 	}
4425 	close(fd);
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;
4432 
4433 	ret = copy_metadata(a, pathname, datafork.s,
4434 #if defined(UF_COMPRESSED)
4435 	    st.st_flags & UF_COMPRESSED);
4436 #else
4437 	    0);
4438 #endif
4439 	if (ret == ARCHIVE_OK) {
4440 		unlink(pathname);
4441 		ret = ARCHIVE_EOF;
4442 	}
4443 skip_appledouble:
4444 	archive_string_free(&datafork);
4445 	return (ret);
4446 }
4447 #endif
4448 
4449 #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4450 /*
4451  * Restore extended attributes -  Linux, Darwin and AIX implementations:
4452  * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4453  */
4454 static int
4455 set_xattrs(struct archive_write_disk *a)
4456 {
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);
4461 	short fail = 0;
4462 
4463 	archive_string_init(&errlist);
4464 
4465 	while (i--) {
4466 		const char *name;
4467 		const void *value;
4468 		size_t size;
4469 		int e;
4470 
4471 		archive_entry_xattr_next(entry, &name, &value, &size);
4472 
4473 		if (name == NULL)
4474 			continue;
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))
4480 			continue;
4481 		if (strncmp(name, "trusted.SGI_", 12) == 0 &&
4482 		   (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
4483 		    strcmp(name + 12, "ACL_FILE") == 0))
4484 			continue;
4485 
4486 		/* Linux: xfsroot namespace is obsolete and unsupported */
4487 		if (strncmp(name, "xfsroot.", 8) == 0) {
4488 			fail = 1;
4489 			archive_strcat(&errlist, name);
4490 			archive_strappend_char(&errlist, ' ');
4491 			continue;
4492 		}
4493 #endif
4494 
4495 		if (a->fd >= 0) {
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);
4502 #endif
4503 		} else {
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);
4513 #endif
4514 		}
4515 		if (e == -1) {
4516 			ret = ARCHIVE_WARN;
4517 			archive_strcat(&errlist, name);
4518 			archive_strappend_char(&errlist, ' ');
4519 			if (errno != ENOTSUP && errno != ENOSYS)
4520 				fail = 1;
4521 		}
4522 	}
4523 
4524 	if (ret == ARCHIVE_WARN) {
4525 		if (fail && errlist.length > 0) {
4526 			errlist.length--;
4527 			errlist.s[errlist.length] = '\0';
4528 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4529 			    "Cannot restore extended attributes: %s",
4530 			    errlist.s);
4531 		} else
4532 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4533 			    "Cannot restore extended "
4534 			    "attributes on this file system.");
4535 	}
4536 
4537 	archive_string_free(&errlist);
4538 	return (ret);
4539 }
4540 #elif ARCHIVE_XATTR_FREEBSD
4541 /*
4542  * Restore extended attributes -  FreeBSD implementation
4543  */
4544 static int
4545 set_xattrs(struct archive_write_disk *a)
4546 {
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);
4551 	short fail = 0;
4552 
4553 	archive_string_init(&errlist);
4554 
4555 	while (i--) {
4556 		const char *name;
4557 		const void *value;
4558 		size_t size;
4559 		archive_entry_xattr_next(entry, &name, &value, &size);
4560 		if (name != NULL) {
4561 			ssize_t e;
4562 			int namespace;
4563 
4564 			namespace = EXTATTR_NAMESPACE_USER;
4565 
4566 			if (strncmp(name, "user.", 5) == 0) {
4567 				/* "user." attributes go to user namespace */
4568 				name += 5;
4569 				namespace = EXTATTR_NAMESPACE_USER;
4570 			} else if (strncmp(name, "system.", 7) == 0) {
4571 				name += 7;
4572 				namespace = EXTATTR_NAMESPACE_SYSTEM;
4573 				if (!strcmp(name, "nfs4.acl") ||
4574 				    !strcmp(name, "posix1e.acl_access") ||
4575 				    !strcmp(name, "posix1e.acl_default"))
4576 					continue;
4577 			} else {
4578 				/* Other namespaces are unsupported */
4579 				archive_strcat(&errlist, name);
4580 				archive_strappend_char(&errlist, ' ');
4581 				fail = 1;
4582 				ret = ARCHIVE_WARN;
4583 				continue;
4584 			}
4585 
4586 			if (a->fd >= 0) {
4587 				/*
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.
4592 				 *
4593 				 * We can detect the failure by
4594 				 * manually setting errno prior to the
4595 				 * call and checking after.
4596 				 *
4597 				 * If errno remains zero, fake the
4598 				 * return value by setting e to size.
4599 				 *
4600 				 * This is a hack for now until I
4601 				 * (Shawn Webb) get FreeBSD to fix the
4602 				 * issue, if that's even possible.
4603 				 */
4604 				errno = 0;
4605 				e = extattr_set_fd(a->fd, namespace, name,
4606 				    value, size);
4607 				if (e == 0 && errno == 0) {
4608 					e = size;
4609 				}
4610 			} else {
4611 				e = extattr_set_link(
4612 				    archive_entry_pathname(entry), namespace,
4613 				    name, value, size);
4614 			}
4615 			if (e != (ssize_t)size) {
4616 				archive_strcat(&errlist, name);
4617 				archive_strappend_char(&errlist, ' ');
4618 				ret = ARCHIVE_WARN;
4619 				if (errno != ENOTSUP && errno != ENOSYS)
4620 					fail = 1;
4621 			}
4622 		}
4623 	}
4624 
4625 	if (ret == ARCHIVE_WARN) {
4626 		if (fail && errlist.length > 0) {
4627 			errlist.length--;
4628 			errlist.s[errlist.length] = '\0';
4629 
4630 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4631 			    "Cannot restore extended attributes: %s",
4632 			    errlist.s);
4633 		} else
4634 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4635 			    "Cannot restore extended "
4636 			    "attributes on this file system.");
4637 	}
4638 
4639 	archive_string_free(&errlist);
4640 	return (ret);
4641 }
4642 #else
4643 /*
4644  * Restore extended attributes - stub implementation for unsupported systems
4645  */
4646 static int
4647 set_xattrs(struct archive_write_disk *a)
4648 {
4649 	static int warning_done = 0;
4650 
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) {
4654 		warning_done = 1;
4655 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4656 		    "Cannot restore extended attributes on this system");
4657 		return (ARCHIVE_WARN);
4658 	}
4659 	/* Warning was already emitted; suppress further warnings. */
4660 	return (ARCHIVE_OK);
4661 }
4662 #endif
4663 
4664 /*
4665  * Test if file on disk is older than entry.
4666  */
4667 static int
4668 older(struct stat *st, struct archive_entry *entry)
4669 {
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)))
4673 		return (1);
4674 	/* Definitely younger. */
4675 	if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4676 		return (0);
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))
4681 		return (1);
4682 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4683 	/* Definitely older. */
4684 	if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4685 		return (1);
4686 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4687 	/* older. */
4688 	if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4689 		return (1);
4690 #elif HAVE_STRUCT_STAT_ST_UMTIME
4691 	/* older. */
4692 	if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4693 		return (1);
4694 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4695 	/* older. */
4696 	if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4697 		return (1);
4698 #else
4699 	/* This system doesn't have high-res timestamps. */
4700 #endif
4701 	/* Same age or newer, so not older. */
4702 	return (0);
4703 }
4704 
4705 #ifndef ARCHIVE_ACL_SUPPORT
4706 int
4707 archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4708     struct archive_acl *abstract_acl, __LA_MODE_T mode)
4709 {
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);
4716 }
4717 #endif
4718 
4719 #endif /* !_WIN32 || __CYGWIN__ */
4720 
4721