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 static void close_file_descriptor(struct archive_write_disk *);
401 
402 static int	_archive_write_disk_close(struct archive *);
403 static int	_archive_write_disk_free(struct archive *);
404 static int	_archive_write_disk_header(struct archive *,
405 		    struct archive_entry *);
406 static int64_t	_archive_write_disk_filter_bytes(struct archive *, int);
407 static int	_archive_write_disk_finish_entry(struct archive *);
408 static ssize_t	_archive_write_disk_data(struct archive *, const void *,
409 		    size_t);
410 static ssize_t	_archive_write_disk_data_block(struct archive *, const void *,
411 		    size_t, int64_t);
412 
413 static int
414 la_mktemp(struct archive_write_disk *a)
415 {
416 	int oerrno, fd;
417 	mode_t mode;
418 
419 	archive_string_empty(&a->_tmpname_data);
420 	archive_string_sprintf(&a->_tmpname_data, "%s.XXXXXX", a->name);
421 	a->tmpname = a->_tmpname_data.s;
422 
423 	fd = __archive_mkstemp(a->tmpname);
424 	if (fd == -1)
425 		return -1;
426 
427 	mode = a->mode & 0777 & ~a->user_umask;
428 	if (fchmod(fd, mode) == -1) {
429 		oerrno = errno;
430 		close(fd);
431 		errno = oerrno;
432 		return -1;
433 	}
434 	return fd;
435 }
436 
437 static int
438 la_opendirat(int fd, const char *path) {
439 	const int flags = O_CLOEXEC
440 #if defined(O_BINARY)
441 	    | O_BINARY
442 #endif
443 #if defined(O_DIRECTORY)
444 	    | O_DIRECTORY
445 #endif
446 #if defined(O_PATH)
447 	    | O_PATH
448 #elif defined(O_SEARCH)
449 	    | O_SEARCH
450 #elif defined(__FreeBSD__) && defined(O_EXEC)
451 	    | O_EXEC
452 #else
453 	    | O_RDONLY
454 #endif
455 	    ;
456 
457 #if !defined(HAVE_OPENAT)
458 	if (fd != AT_FDCWD) {
459 		errno = ENOTSUP;
460 		return (-1);
461 	} else
462 		return (open(path, flags));
463 #else
464 	return (openat(fd, path, flags));
465 #endif
466 }
467 
468 static int
469 la_verify_filetype(mode_t mode, __LA_MODE_T filetype) {
470 	int ret = 0;
471 
472 	switch (filetype) {
473 	case AE_IFREG:
474 		ret = (S_ISREG(mode));
475 		break;
476 	case AE_IFDIR:
477 		ret = (S_ISDIR(mode));
478 		break;
479 	case AE_IFLNK:
480 		ret = (S_ISLNK(mode));
481 		break;
482 	case AE_IFSOCK:
483 		ret = (S_ISSOCK(mode));
484 		break;
485 	case AE_IFCHR:
486 		ret = (S_ISCHR(mode));
487 		break;
488 	case AE_IFBLK:
489 		ret = (S_ISBLK(mode));
490 		break;
491 	case AE_IFIFO:
492 		ret = (S_ISFIFO(mode));
493 		break;
494 	default:
495 		break;
496 	}
497 
498 	return (ret);
499 }
500 
501 static int
502 lazy_stat(struct archive_write_disk *a)
503 {
504 	if (a->pst != NULL) {
505 		/* Already have stat() data available. */
506 		return (ARCHIVE_OK);
507 	}
508 #ifdef HAVE_FSTAT
509 	if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
510 		a->pst = &a->st;
511 		return (ARCHIVE_OK);
512 	}
513 #endif
514 	/*
515 	 * XXX At this point, symlinks should not be hit, otherwise
516 	 * XXX a race occurred.  Do we want to check explicitly for that?
517 	 */
518 #ifdef HAVE_LSTAT
519 	if (lstat(a->name, &a->st) == 0)
520 #else
521 	if (la_stat(a->name, &a->st) == 0)
522 #endif
523 	{
524 		a->pst = &a->st;
525 		return (ARCHIVE_OK);
526 	}
527 	archive_set_error(&a->archive, errno, "Couldn't stat file");
528 	return (ARCHIVE_WARN);
529 }
530 
531 static const struct archive_vtable
532 archive_write_disk_vtable = {
533 	.archive_close = _archive_write_disk_close,
534 	.archive_filter_bytes = _archive_write_disk_filter_bytes,
535 	.archive_free = _archive_write_disk_free,
536 	.archive_write_header = _archive_write_disk_header,
537 	.archive_write_finish_entry = _archive_write_disk_finish_entry,
538 	.archive_write_data = _archive_write_disk_data,
539 	.archive_write_data_block = _archive_write_disk_data_block,
540 };
541 
542 static int64_t
543 _archive_write_disk_filter_bytes(struct archive *_a, int n)
544 {
545 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
546 	(void)n; /* UNUSED */
547 	if (n == -1 || n == 0)
548 		return (a->total_bytes_written);
549 	return (-1);
550 }
551 
552 
553 int
554 archive_write_disk_set_options(struct archive *_a, int flags)
555 {
556 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
557 
558 	a->flags = flags;
559 	return (ARCHIVE_OK);
560 }
561 
562 
563 /*
564  * Extract this entry to disk.
565  *
566  * TODO: Validate hardlinks.  According to the standards, we're
567  * supposed to check each extracted hardlink and squawk if it refers
568  * to a file that we didn't restore.  I'm not entirely convinced this
569  * is a good idea, but more importantly: Is there any way to validate
570  * hardlinks without keeping a complete list of filenames from the
571  * entire archive?? Ugh.
572  *
573  */
574 static int
575 _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
576 {
577 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
578 	struct fixup_entry *fe;
579 	const char *linkname;
580 	int ret, r;
581 
582 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
583 	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
584 	    "archive_write_disk_header");
585 	archive_clear_error(&a->archive);
586 	if (a->archive.state & ARCHIVE_STATE_DATA) {
587 		r = _archive_write_disk_finish_entry(&a->archive);
588 		if (r == ARCHIVE_FATAL)
589 			return (r);
590 	}
591 
592 	/* Set up for this particular entry. */
593 	a->pst = NULL;
594 	a->current_fixup = NULL;
595 	a->deferred = 0;
596 	if (a->entry) {
597 		archive_entry_free(a->entry);
598 		a->entry = NULL;
599 	}
600 	a->entry = archive_entry_clone(entry);
601 	a->fd = -1;
602 	a->fd_offset = 0;
603 	a->offset = 0;
604 	a->restore_pwd = -1;
605 	a->uid = a->user_uid;
606 	a->mode = archive_entry_mode(a->entry);
607 	if (archive_entry_size_is_set(a->entry))
608 		a->filesize = archive_entry_size(a->entry);
609 	else
610 		a->filesize = -1;
611 	archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
612 	a->name = a->_name_data.s;
613 	archive_clear_error(&a->archive);
614 
615 	/*
616 	 * Clean up the requested path.  This is necessary for correct
617 	 * dir restores; the dir restore logic otherwise gets messed
618 	 * up by nonsense like "dir/.".
619 	 */
620 	ret = cleanup_pathname(a);
621 	if (ret != ARCHIVE_OK)
622 		return (ret);
623 
624 	/*
625 	 * Check if we have a hardlink that points to itself.
626 	 */
627 	linkname = archive_entry_hardlink(a->entry);
628 	if (linkname != NULL && strcmp(a->name, linkname) == 0) {
629 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
630 		    "Skipping hardlink pointing to itself: %s",
631 		    a->name);
632 		return (ARCHIVE_WARN);
633 	}
634 
635 	/*
636 	 * Query the umask so we get predictable mode settings.
637 	 * This gets done on every call to _write_header in case the
638 	 * user edits their umask during the extraction for some
639 	 * reason.
640 	 */
641 	umask(a->user_umask = umask(0));
642 
643 	/* Figure out what we need to do for this entry. */
644 	a->todo = TODO_MODE_BASE;
645 	if (a->flags & ARCHIVE_EXTRACT_PERM) {
646 		a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
647 		/*
648 		 * SGID requires an extra "check" step because we
649 		 * cannot easily predict the GID that the system will
650 		 * assign.  (Different systems assign GIDs to files
651 		 * based on a variety of criteria, including process
652 		 * credentials and the gid of the enclosing
653 		 * directory.)  We can only restore the SGID bit if
654 		 * the file has the right GID, and we only know the
655 		 * GID if we either set it (see set_ownership) or if
656 		 * we've actually called stat() on the file after it
657 		 * was restored.  Since there are several places at
658 		 * which we might verify the GID, we need a TODO bit
659 		 * to keep track.
660 		 */
661 		if (a->mode & S_ISGID)
662 			a->todo |= TODO_SGID | TODO_SGID_CHECK;
663 		/*
664 		 * Verifying the SUID is simpler, but can still be
665 		 * done in multiple ways, hence the separate "check" bit.
666 		 */
667 		if (a->mode & S_ISUID)
668 			a->todo |= TODO_SUID | TODO_SUID_CHECK;
669 	} else {
670 		/*
671 		 * User didn't request full permissions, so don't
672 		 * restore SUID, SGID bits and obey umask.
673 		 */
674 		a->mode &= ~S_ISUID;
675 		a->mode &= ~S_ISGID;
676 		a->mode &= ~S_ISVTX;
677 		a->mode &= ~a->user_umask;
678 	}
679 	if (a->flags & ARCHIVE_EXTRACT_OWNER)
680 		a->todo |= TODO_OWNER;
681 	if (a->flags & ARCHIVE_EXTRACT_TIME)
682 		a->todo |= TODO_TIMES;
683 	if (a->flags & ARCHIVE_EXTRACT_ACL) {
684 #if ARCHIVE_ACL_DARWIN
685 		/*
686 		 * On MacOS, platform ACLs get stored in mac_metadata, too.
687 		 * If we intend to extract mac_metadata and it is present
688 		 * we skip extracting libarchive NFSv4 ACLs.
689 		 */
690 		size_t metadata_size;
691 
692 		if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
693 		    archive_entry_mac_metadata(a->entry,
694 		    &metadata_size) == NULL || metadata_size == 0)
695 #endif
696 #if ARCHIVE_ACL_LIBRICHACL
697 		/*
698 		 * RichACLs are stored in an extended attribute.
699 		 * If we intend to extract extended attributes and have this
700 		 * attribute we skip extracting libarchive NFSv4 ACLs.
701 		 */
702 		short extract_acls = 1;
703 		if (a->flags & ARCHIVE_EXTRACT_XATTR && (
704 		    archive_entry_acl_types(a->entry) &
705 		    ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
706 			const char *attr_name;
707 			const void *attr_value;
708 			size_t attr_size;
709 			int i = archive_entry_xattr_reset(a->entry);
710 			while (i--) {
711 				archive_entry_xattr_next(a->entry, &attr_name,
712 				    &attr_value, &attr_size);
713 				if (attr_name != NULL && attr_value != NULL &&
714 				    attr_size > 0 && strcmp(attr_name,
715 				    "trusted.richacl") == 0) {
716 					extract_acls = 0;
717 					break;
718 				}
719 			}
720 		}
721 		if (extract_acls)
722 #endif
723 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
724 		{
725 #endif
726 		if (archive_entry_filetype(a->entry) == AE_IFDIR)
727 			a->deferred |= TODO_ACLS;
728 		else
729 			a->todo |= TODO_ACLS;
730 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
731 		}
732 #endif
733 	}
734 	if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
735 		if (archive_entry_filetype(a->entry) == AE_IFDIR)
736 			a->deferred |= TODO_MAC_METADATA;
737 		else
738 			a->todo |= TODO_MAC_METADATA;
739 	}
740 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
741 	if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
742 		unsigned long set, clear;
743 		archive_entry_fflags(a->entry, &set, &clear);
744 		if ((set & ~clear) & UF_COMPRESSED) {
745 			a->todo |= TODO_HFS_COMPRESSION;
746 			a->decmpfs_block_count = (unsigned)-1;
747 		}
748 	}
749 	if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
750 	    (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
751 		a->todo |= TODO_HFS_COMPRESSION;
752 		a->decmpfs_block_count = (unsigned)-1;
753 	}
754 	{
755 		const char *p;
756 
757 		/* Check if the current file name is a type of the
758 		 * resource fork file. */
759 		p = strrchr(a->name, '/');
760 		if (p == NULL)
761 			p = a->name;
762 		else
763 			p++;
764 		if (p[0] == '.' && p[1] == '_') {
765 			/* Do not compress "._XXX" files. */
766 			a->todo &= ~TODO_HFS_COMPRESSION;
767 			if (a->filesize > 0)
768 				a->todo |= TODO_APPLEDOUBLE;
769 		}
770 	}
771 #endif
772 
773 	if (a->flags & ARCHIVE_EXTRACT_XATTR) {
774 #if ARCHIVE_XATTR_DARWIN
775 		/*
776 		 * On MacOS, extended attributes get stored in mac_metadata,
777 		 * too. If we intend to extract mac_metadata and it is present
778 		 * we skip extracting extended attributes.
779 		 */
780 		size_t metadata_size;
781 
782 		if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
783 		    archive_entry_mac_metadata(a->entry,
784 		    &metadata_size) == NULL || metadata_size == 0)
785 #endif
786 		a->todo |= TODO_XATTR;
787 	}
788 	if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
789 		a->todo |= TODO_FFLAGS;
790 	if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
791 		ret = check_symlinks(a);
792 		if (ret != ARCHIVE_OK)
793 			return (ret);
794 	}
795 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
796 	/* If path exceeds PATH_MAX, shorten the path. */
797 	edit_deep_directories(a);
798 #endif
799 
800 	ret = restore_entry(a);
801 
802 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
803 	/*
804 	 * Check if the filesystem the file is restoring on supports
805 	 * HFS+ Compression. If not, cancel HFS+ Compression.
806 	 */
807 	if (a->todo | TODO_HFS_COMPRESSION) {
808 		/*
809 		 * NOTE: UF_COMPRESSED is ignored even if the filesystem
810 		 * supports HFS+ Compression because the file should
811 		 * have at least an extended attribute "com.apple.decmpfs"
812 		 * before the flag is set to indicate that the file have
813 		 * been compressed. If the filesystem does not support
814 		 * HFS+ Compression the system call will fail.
815 		 */
816 		if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
817 			a->todo &= ~TODO_HFS_COMPRESSION;
818 	}
819 #endif
820 
821 	/*
822 	 * TODO: There are rumours that some extended attributes must
823 	 * be restored before file data is written.  If this is true,
824 	 * then we either need to write all extended attributes both
825 	 * before and after restoring the data, or find some rule for
826 	 * determining which must go first and which last.  Due to the
827 	 * many ways people are using xattrs, this may prove to be an
828 	 * intractable problem.
829 	 */
830 
831 #ifdef HAVE_FCHDIR
832 	/* If we changed directory above, restore it here. */
833 	if (a->restore_pwd >= 0) {
834 		r = fchdir(a->restore_pwd);
835 		if (r != 0) {
836 			archive_set_error(&a->archive, errno,
837 			    "chdir() failure");
838 			ret = ARCHIVE_FATAL;
839 		}
840 		close(a->restore_pwd);
841 		a->restore_pwd = -1;
842 	}
843 #endif
844 
845 	/*
846 	 * Fixup uses the unedited pathname from archive_entry_pathname(),
847 	 * because it is relative to the base dir and the edited path
848 	 * might be relative to some intermediate dir as a result of the
849 	 * deep restore logic.
850 	 */
851 	if (a->deferred & TODO_MODE) {
852 		fe = current_fixup(a, archive_entry_pathname(entry));
853 		if (fe == NULL)
854 			return (ARCHIVE_FATAL);
855 		fe->filetype = archive_entry_filetype(entry);
856 		fe->fixup |= TODO_MODE_BASE;
857 		fe->mode = a->mode;
858 	}
859 
860 	if ((a->deferred & TODO_TIMES)
861 		&& (archive_entry_mtime_is_set(entry)
862 		    || archive_entry_atime_is_set(entry))) {
863 		fe = current_fixup(a, archive_entry_pathname(entry));
864 		if (fe == NULL)
865 			return (ARCHIVE_FATAL);
866 		fe->filetype = archive_entry_filetype(entry);
867 		fe->mode = a->mode;
868 		fe->fixup |= TODO_TIMES;
869 		if (archive_entry_atime_is_set(entry)) {
870 			fe->atime = archive_entry_atime(entry);
871 			fe->atime_nanos = archive_entry_atime_nsec(entry);
872 		} else {
873 			/* If atime is unset, use start time. */
874 			fe->atime = a->start_time;
875 			fe->atime_nanos = 0;
876 		}
877 		if (archive_entry_mtime_is_set(entry)) {
878 			fe->mtime = archive_entry_mtime(entry);
879 			fe->mtime_nanos = archive_entry_mtime_nsec(entry);
880 		} else {
881 			/* If mtime is unset, use start time. */
882 			fe->mtime = a->start_time;
883 			fe->mtime_nanos = 0;
884 		}
885 		if (archive_entry_birthtime_is_set(entry)) {
886 			fe->birthtime = archive_entry_birthtime(entry);
887 			fe->birthtime_nanos = archive_entry_birthtime_nsec(
888 			    entry);
889 		} else {
890 			/* If birthtime is unset, use mtime. */
891 			fe->birthtime = fe->mtime;
892 			fe->birthtime_nanos = fe->mtime_nanos;
893 		}
894 	}
895 
896 	if (a->deferred & TODO_ACLS) {
897 		fe = current_fixup(a, archive_entry_pathname(entry));
898 		if (fe == NULL)
899 			return (ARCHIVE_FATAL);
900 		fe->filetype = archive_entry_filetype(entry);
901 		fe->fixup |= TODO_ACLS;
902 		archive_acl_copy(&fe->acl, archive_entry_acl(entry));
903 	}
904 
905 	if (a->deferred & TODO_MAC_METADATA) {
906 		const void *metadata;
907 		size_t metadata_size;
908 		metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
909 		if (metadata != NULL && metadata_size > 0) {
910 			fe = current_fixup(a, archive_entry_pathname(entry));
911 			if (fe == NULL)
912 				return (ARCHIVE_FATAL);
913 			fe->filetype = archive_entry_filetype(entry);
914 			fe->mac_metadata = malloc(metadata_size);
915 			if (fe->mac_metadata != NULL) {
916 				memcpy(fe->mac_metadata, metadata,
917 				    metadata_size);
918 				fe->mac_metadata_size = metadata_size;
919 				fe->fixup |= TODO_MAC_METADATA;
920 			}
921 		}
922 	}
923 
924 	if (a->deferred & TODO_FFLAGS) {
925 		fe = current_fixup(a, archive_entry_pathname(entry));
926 		if (fe == NULL)
927 			return (ARCHIVE_FATAL);
928 		fe->filetype = archive_entry_filetype(entry);
929 		fe->fixup |= TODO_FFLAGS;
930 		/* TODO: Complete this.. defer fflags from below. */
931 	}
932 
933 	/* We've created the object and are ready to pour data into it. */
934 	if (ret >= ARCHIVE_WARN)
935 		a->archive.state = ARCHIVE_STATE_DATA;
936 	/*
937 	 * If it's not open, tell our client not to try writing.
938 	 * In particular, dirs, links, etc, don't get written to.
939 	 */
940 	if (a->fd < 0) {
941 		archive_entry_set_size(entry, 0);
942 		a->filesize = 0;
943 	}
944 
945 	return (ret);
946 }
947 
948 int
949 archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
950 {
951 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
952 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
953 	    ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
954 	a->skip_file_set = 1;
955 	a->skip_file_dev = d;
956 	a->skip_file_ino = i;
957 	return (ARCHIVE_OK);
958 }
959 
960 static ssize_t
961 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
962 {
963 	uint64_t start_size = size;
964 	ssize_t bytes_written = 0;
965 	ssize_t block_size = 0, bytes_to_write;
966 
967 	if (size == 0)
968 		return (ARCHIVE_OK);
969 
970 	if (a->filesize == 0 || a->fd < 0) {
971 		archive_set_error(&a->archive, 0,
972 		    "Attempt to write to an empty file");
973 		return (ARCHIVE_WARN);
974 	}
975 
976 	if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
977 #if HAVE_STRUCT_STAT_ST_BLKSIZE
978 		int r;
979 		if ((r = lazy_stat(a)) != ARCHIVE_OK)
980 			return (r);
981 		block_size = a->pst->st_blksize;
982 #else
983 		/* XXX TODO XXX Is there a more appropriate choice here ? */
984 		/* This needn't match the filesystem allocation size. */
985 		block_size = 16*1024;
986 #endif
987 	}
988 
989 	/* If this write would run beyond the file size, truncate it. */
990 	if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
991 		start_size = size = (size_t)(a->filesize - a->offset);
992 
993 	/* Write the data. */
994 	while (size > 0) {
995 		if (block_size == 0) {
996 			bytes_to_write = size;
997 		} else {
998 			/* We're sparsifying the file. */
999 			const char *p, *end;
1000 			int64_t block_end;
1001 
1002 			/* Skip leading zero bytes. */
1003 			for (p = buff, end = buff + size; p < end; ++p) {
1004 				if (*p != '\0')
1005 					break;
1006 			}
1007 			a->offset += p - buff;
1008 			size -= p - buff;
1009 			buff = p;
1010 			if (size == 0)
1011 				break;
1012 
1013 			/* Calculate next block boundary after offset. */
1014 			block_end
1015 			    = (a->offset / block_size + 1) * block_size;
1016 
1017 			/* If the adjusted write would cross block boundary,
1018 			 * truncate it to the block boundary. */
1019 			bytes_to_write = size;
1020 			if (a->offset + bytes_to_write > block_end)
1021 				bytes_to_write = block_end - a->offset;
1022 		}
1023 		/* Seek if necessary to the specified offset. */
1024 		if (a->offset != a->fd_offset) {
1025 			if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
1026 				archive_set_error(&a->archive, errno,
1027 				    "Seek failed");
1028 				return (ARCHIVE_FATAL);
1029 			}
1030 			a->fd_offset = a->offset;
1031 		}
1032 		bytes_written = write(a->fd, buff, bytes_to_write);
1033 		if (bytes_written < 0) {
1034 			archive_set_error(&a->archive, errno, "Write failed");
1035 			return (ARCHIVE_WARN);
1036 		}
1037 		buff += bytes_written;
1038 		size -= bytes_written;
1039 		a->total_bytes_written += bytes_written;
1040 		a->offset += bytes_written;
1041 		a->fd_offset = a->offset;
1042 	}
1043 	return (start_size - size);
1044 }
1045 
1046 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
1047 	&& defined(HAVE_ZLIB_H)
1048 
1049 /*
1050  * Set UF_COMPRESSED file flag.
1051  * This have to be called after hfs_write_decmpfs() because if the
1052  * file does not have "com.apple.decmpfs" xattr the flag is ignored.
1053  */
1054 static int
1055 hfs_set_compressed_fflag(struct archive_write_disk *a)
1056 {
1057 	int r;
1058 
1059 	if ((r = lazy_stat(a)) != ARCHIVE_OK)
1060 		return (r);
1061 
1062 	a->st.st_flags |= UF_COMPRESSED;
1063 	if (fchflags(a->fd, a->st.st_flags) != 0) {
1064 		archive_set_error(&a->archive, errno,
1065 		    "Failed to set UF_COMPRESSED file flag");
1066 		return (ARCHIVE_WARN);
1067 	}
1068 	return (ARCHIVE_OK);
1069 }
1070 
1071 /*
1072  * HFS+ Compression decmpfs
1073  *
1074  *     +------------------------------+ +0
1075  *     |      Magic(LE 4 bytes)       |
1076  *     +------------------------------+
1077  *     |      Type(LE 4 bytes)        |
1078  *     +------------------------------+
1079  *     | Uncompressed size(LE 8 bytes)|
1080  *     +------------------------------+ +16
1081  *     |                              |
1082  *     |       Compressed data        |
1083  *     |  (Placed only if Type == 3)  |
1084  *     |                              |
1085  *     +------------------------------+  +3802 = MAX_DECMPFS_XATTR_SIZE
1086  *
1087  *  Type is 3: decmpfs has compressed data.
1088  *  Type is 4: Resource Fork has compressed data.
1089  */
1090 /*
1091  * Write "com.apple.decmpfs"
1092  */
1093 static int
1094 hfs_write_decmpfs(struct archive_write_disk *a)
1095 {
1096 	int r;
1097 	uint32_t compression_type;
1098 
1099 	r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1100 	    a->decmpfs_attr_size, 0, 0);
1101 	if (r < 0) {
1102 		archive_set_error(&a->archive, errno,
1103 		    "Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
1104 		compression_type = archive_le32dec(
1105 		    &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
1106 		if (compression_type == CMP_RESOURCE_FORK)
1107 			fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
1108 			    XATTR_SHOWCOMPRESSION);
1109 		return (ARCHIVE_WARN);
1110 	}
1111 	return (ARCHIVE_OK);
1112 }
1113 
1114 /*
1115  * HFS+ Compression Resource Fork
1116  *
1117  *     +-----------------------------+
1118  *     |     Header(260 bytes)       |
1119  *     +-----------------------------+
1120  *     |   Block count(LE 4 bytes)   |
1121  *     +-----------------------------+  --+
1122  * +-- |     Offset (LE 4 bytes)     |    |
1123  * |   | [distance from Block count] |    | Block 0
1124  * |   +-----------------------------+    |
1125  * |   | Compressed size(LE 4 bytes) |    |
1126  * |   +-----------------------------+  --+
1127  * |   |                             |
1128  * |   |      ..................     |
1129  * |   |                             |
1130  * |   +-----------------------------+  --+
1131  * |   |     Offset (LE 4 bytes)     |    |
1132  * |   +-----------------------------+    | Block (Block count -1)
1133  * |   | Compressed size(LE 4 bytes) |    |
1134  * +-> +-----------------------------+  --+
1135  *     |   Compressed data(n bytes)  |  Block 0
1136  *     +-----------------------------+
1137  *     |                             |
1138  *     |      ..................     |
1139  *     |                             |
1140  *     +-----------------------------+
1141  *     |   Compressed data(n bytes)  |  Block (Block count -1)
1142  *     +-----------------------------+
1143  *     |      Footer(50 bytes)       |
1144  *     +-----------------------------+
1145  *
1146  */
1147 /*
1148  * Write the header of "com.apple.ResourceFork"
1149  */
1150 static int
1151 hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1152     size_t bytes, uint32_t position)
1153 {
1154 	int ret;
1155 
1156 	ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1157 	    position, a->rsrc_xattr_options);
1158 	if (ret < 0) {
1159 		archive_set_error(&a->archive, errno,
1160 		    "Cannot restore xattr: %s at %u pos %u bytes",
1161 		    XATTR_RESOURCEFORK_NAME,
1162 		    (unsigned)position,
1163 		    (unsigned)bytes);
1164 		return (ARCHIVE_WARN);
1165 	}
1166 	a->rsrc_xattr_options &= ~XATTR_CREATE;
1167 	return (ARCHIVE_OK);
1168 }
1169 
1170 static int
1171 hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1172 {
1173 	int ret;
1174 
1175 	ret = hfs_write_resource_fork(a, a->compressed_buffer,
1176 	    bytes_compressed, a->compressed_rsrc_position);
1177 	if (ret == ARCHIVE_OK)
1178 		a->compressed_rsrc_position += bytes_compressed;
1179 	return (ret);
1180 }
1181 
1182 static int
1183 hfs_write_resource_fork_header(struct archive_write_disk *a)
1184 {
1185 	unsigned char *buff;
1186 	uint32_t rsrc_bytes;
1187 	uint32_t rsrc_header_bytes;
1188 
1189 	/*
1190 	 * Write resource fork header + block info.
1191 	 */
1192 	buff = a->resource_fork;
1193 	rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1194 	rsrc_header_bytes =
1195 		RSRC_H_SIZE +		/* Header base size. */
1196 		4 +			/* Block count. */
1197 		(a->decmpfs_block_count * 8);/* Block info */
1198 	archive_be32enc(buff, 0x100);
1199 	archive_be32enc(buff + 4, rsrc_bytes);
1200 	archive_be32enc(buff + 8, rsrc_bytes - 256);
1201 	archive_be32enc(buff + 12, 0x32);
1202 	memset(buff + 16, 0, 240);
1203 	archive_be32enc(buff + 256, rsrc_bytes - 260);
1204 	return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
1205 }
1206 
1207 static size_t
1208 hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1209 {
1210 	static const char rsrc_footer[RSRC_F_SIZE] = {
1211 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1212 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1213 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1214 		0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c',  'm',
1215 		'p', 'f',   0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
1216 		0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1217 		0x00, 0x00
1218 	};
1219 	if (buff_size < sizeof(rsrc_footer))
1220 		return (0);
1221 	memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1222 	return (sizeof(rsrc_footer));
1223 }
1224 
1225 static int
1226 hfs_reset_compressor(struct archive_write_disk *a)
1227 {
1228 	int ret;
1229 
1230 	if (a->stream_valid)
1231 		ret = deflateReset(&a->stream);
1232 	else
1233 		ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1234 
1235 	if (ret != Z_OK) {
1236 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1237 		    "Failed to initialize compressor");
1238 		return (ARCHIVE_FATAL);
1239 	} else
1240 		a->stream_valid = 1;
1241 
1242 	return (ARCHIVE_OK);
1243 }
1244 
1245 static int
1246 hfs_decompress(struct archive_write_disk *a)
1247 {
1248 	uint32_t *block_info;
1249 	unsigned int block_count;
1250 	uint32_t data_pos, data_size;
1251 	ssize_t r;
1252 	ssize_t bytes_written, bytes_to_write;
1253 	unsigned char *b;
1254 
1255 	block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1256 	block_count = archive_le32dec(block_info++);
1257 	while (block_count--) {
1258 		data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
1259 		data_size = archive_le32dec(block_info++);
1260 		r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
1261 		    a->compressed_buffer, data_size, data_pos, 0);
1262 		if (r != data_size)  {
1263 			archive_set_error(&a->archive,
1264 			    (r < 0)?errno:ARCHIVE_ERRNO_MISC,
1265 			    "Failed to read resource fork");
1266 			return (ARCHIVE_WARN);
1267 		}
1268 		if (a->compressed_buffer[0] == 0xff) {
1269 			bytes_to_write = data_size -1;
1270 			b = a->compressed_buffer + 1;
1271 		} else {
1272 			uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1273 			int zr;
1274 
1275 			zr = uncompress((Bytef *)a->uncompressed_buffer,
1276 			    &dest_len, a->compressed_buffer, data_size);
1277 			if (zr != Z_OK) {
1278 				archive_set_error(&a->archive,
1279 				    ARCHIVE_ERRNO_MISC,
1280 				    "Failed to decompress resource fork");
1281 				return (ARCHIVE_WARN);
1282 			}
1283 			bytes_to_write = dest_len;
1284 			b = (unsigned char *)a->uncompressed_buffer;
1285 		}
1286 		do {
1287 			bytes_written = write(a->fd, b, bytes_to_write);
1288 			if (bytes_written < 0) {
1289 				archive_set_error(&a->archive, errno,
1290 				    "Write failed");
1291 				return (ARCHIVE_WARN);
1292 			}
1293 			bytes_to_write -= bytes_written;
1294 			b += bytes_written;
1295 		} while (bytes_to_write > 0);
1296 	}
1297 	r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1298 	if (r == -1)  {
1299 		archive_set_error(&a->archive, errno,
1300 		    "Failed to remove resource fork");
1301 		return (ARCHIVE_WARN);
1302 	}
1303 	return (ARCHIVE_OK);
1304 }
1305 
1306 static int
1307 hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1308     size_t size)
1309 {
1310 	unsigned char *buffer_compressed;
1311 	size_t bytes_compressed;
1312 	size_t bytes_used;
1313 	int ret;
1314 
1315 	ret = hfs_reset_compressor(a);
1316 	if (ret != ARCHIVE_OK)
1317 		return (ret);
1318 
1319 	if (a->compressed_buffer == NULL) {
1320 		size_t block_size;
1321 
1322 		block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
1323 		    + compressBound(MAX_DECMPFS_BLOCK_SIZE);
1324 		a->compressed_buffer = malloc(block_size);
1325 		if (a->compressed_buffer == NULL) {
1326 			archive_set_error(&a->archive, ENOMEM,
1327 			    "Can't allocate memory for Resource Fork");
1328 			return (ARCHIVE_FATAL);
1329 		}
1330 		a->compressed_buffer_size = block_size;
1331 		a->compressed_buffer_remaining = block_size;
1332 	}
1333 
1334 	buffer_compressed = a->compressed_buffer +
1335 	    a->compressed_buffer_size - a->compressed_buffer_remaining;
1336 	a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
1337 	a->stream.avail_in = size;
1338 	a->stream.next_out = buffer_compressed;
1339 	a->stream.avail_out = a->compressed_buffer_remaining;
1340 	do {
1341 		ret = deflate(&a->stream, Z_FINISH);
1342 		switch (ret) {
1343 		case Z_OK:
1344 		case Z_STREAM_END:
1345 			break;
1346 		default:
1347 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1348 			    "Failed to compress data");
1349 			return (ARCHIVE_FAILED);
1350 		}
1351 	} while (ret == Z_OK);
1352 	bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1353 
1354 	/*
1355 	 * If the compressed size is larger than the original size,
1356 	 * throw away compressed data, use uncompressed data instead.
1357 	 */
1358 	if (bytes_compressed > size) {
1359 		buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1360 		memcpy(buffer_compressed + 1, buff, size);
1361 		bytes_compressed = size + 1;
1362 	}
1363 	a->compressed_buffer_remaining -= bytes_compressed;
1364 
1365 	/*
1366 	 * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
1367 	 * and the block count in the file is only one, store compressed
1368 	 * data to decmpfs xattr instead of the resource fork.
1369 	 */
1370 	if (a->decmpfs_block_count == 1 &&
1371 	    (a->decmpfs_attr_size + bytes_compressed)
1372 	      <= MAX_DECMPFS_XATTR_SIZE) {
1373 		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1374 		    CMP_XATTR);
1375 		memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
1376 		    buffer_compressed, bytes_compressed);
1377 		a->decmpfs_attr_size += bytes_compressed;
1378 		a->compressed_buffer_remaining = a->compressed_buffer_size;
1379 		/*
1380 		 * Finish HFS+ Compression.
1381 		 * - Write the decmpfs xattr.
1382 		 * - Set the UF_COMPRESSED file flag.
1383 		 */
1384 		ret = hfs_write_decmpfs(a);
1385 		if (ret == ARCHIVE_OK)
1386 			ret = hfs_set_compressed_fflag(a);
1387 		return (ret);
1388 	}
1389 
1390 	/* Update block info. */
1391 	archive_le32enc(a->decmpfs_block_info++,
1392 	    a->compressed_rsrc_position_v - RSRC_H_SIZE);
1393 	archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
1394 	a->compressed_rsrc_position_v += bytes_compressed;
1395 
1396 	/*
1397 	 * Write the compressed data to the resource fork.
1398 	 */
1399 	bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
1400 	while (bytes_used >= COMPRESSED_W_SIZE) {
1401 		ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
1402 		if (ret != ARCHIVE_OK)
1403 			return (ret);
1404 		bytes_used -= COMPRESSED_W_SIZE;
1405 		if (bytes_used > COMPRESSED_W_SIZE)
1406 			memmove(a->compressed_buffer,
1407 			    a->compressed_buffer + COMPRESSED_W_SIZE,
1408 			    bytes_used);
1409 		else
1410 			memcpy(a->compressed_buffer,
1411 			    a->compressed_buffer + COMPRESSED_W_SIZE,
1412 			    bytes_used);
1413 	}
1414 	a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1415 
1416 	/*
1417 	 * If the current block is the last block, write the remaining
1418 	 * compressed data and the resource fork footer.
1419 	 */
1420 	if (a->file_remaining_bytes == 0) {
1421 		size_t rsrc_size;
1422 		int64_t bk;
1423 
1424 		/* Append the resource footer. */
1425 		rsrc_size = hfs_set_resource_fork_footer(
1426 		    a->compressed_buffer + bytes_used,
1427 		    a->compressed_buffer_remaining);
1428 		ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
1429 		a->compressed_buffer_remaining = a->compressed_buffer_size;
1430 
1431 		/* If the compressed size is not enough smaller than
1432 		 * the uncompressed size. cancel HFS+ compression.
1433 		 * TODO: study a behavior of ditto utility and improve
1434 		 * the condition to fall back into no HFS+ compression. */
1435 		bk = HFS_BLOCKS(a->compressed_rsrc_position);
1436 		bk += bk >> 7;
1437 		if (bk > HFS_BLOCKS(a->filesize))
1438 			return hfs_decompress(a);
1439 		/*
1440 		 * Write the resourcefork header.
1441 		 */
1442 		if (ret == ARCHIVE_OK)
1443 			ret = hfs_write_resource_fork_header(a);
1444 		/*
1445 		 * Finish HFS+ Compression.
1446 		 * - Write the decmpfs xattr.
1447 		 * - Set the UF_COMPRESSED file flag.
1448 		 */
1449 		if (ret == ARCHIVE_OK)
1450 			ret = hfs_write_decmpfs(a);
1451 		if (ret == ARCHIVE_OK)
1452 			ret = hfs_set_compressed_fflag(a);
1453 	}
1454 	return (ret);
1455 }
1456 
1457 static ssize_t
1458 hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1459     size_t size)
1460 {
1461 	const char *buffer_to_write;
1462 	size_t bytes_to_write;
1463 	int ret;
1464 
1465 	if (a->decmpfs_block_count == (unsigned)-1) {
1466 		void *new_block;
1467 		size_t new_size;
1468 		unsigned int block_count;
1469 
1470 		if (a->decmpfs_header_p == NULL) {
1471 			new_block = malloc(MAX_DECMPFS_XATTR_SIZE
1472 			    + sizeof(uint32_t));
1473 			if (new_block == NULL) {
1474 				archive_set_error(&a->archive, ENOMEM,
1475 				    "Can't allocate memory for decmpfs");
1476 				return (ARCHIVE_FATAL);
1477 			}
1478 			a->decmpfs_header_p = new_block;
1479 		}
1480 		a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1481 		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1482 		    DECMPFS_MAGIC);
1483 		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1484 		    CMP_RESOURCE_FORK);
1485 		archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1486 		    a->filesize);
1487 
1488 		/* Calculate a block count of the file. */
1489 		block_count =
1490 		    (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1491 			MAX_DECMPFS_BLOCK_SIZE;
1492 		/*
1493 		 * Allocate buffer for resource fork.
1494 		 * Set up related pointers;
1495 		 */
1496 		new_size =
1497 		    RSRC_H_SIZE + /* header */
1498 		    4 + /* Block count */
1499 		    (block_count * sizeof(uint32_t) * 2) +
1500 		    RSRC_F_SIZE; /* footer */
1501 		if (new_size > a->resource_fork_allocated_size) {
1502 			new_block = realloc(a->resource_fork, new_size);
1503 			if (new_block == NULL) {
1504 				archive_set_error(&a->archive, ENOMEM,
1505 				    "Can't allocate memory for ResourceFork");
1506 				return (ARCHIVE_FATAL);
1507 			}
1508 			a->resource_fork_allocated_size = new_size;
1509 			a->resource_fork = new_block;
1510 		}
1511 
1512 		/* Allocate uncompressed buffer */
1513 		if (a->uncompressed_buffer == NULL) {
1514 			new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
1515 			if (new_block == NULL) {
1516 				archive_set_error(&a->archive, ENOMEM,
1517 				    "Can't allocate memory for decmpfs");
1518 				return (ARCHIVE_FATAL);
1519 			}
1520 			a->uncompressed_buffer = new_block;
1521 		}
1522 		a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1523 		a->file_remaining_bytes = a->filesize;
1524 		a->compressed_buffer_remaining = a->compressed_buffer_size;
1525 
1526 		/*
1527 		 * Set up a resource fork.
1528 		 */
1529 		a->rsrc_xattr_options = XATTR_CREATE;
1530 		/* Get the position where we are going to set a bunch
1531 		 * of block info. */
1532 		a->decmpfs_block_info =
1533 		    (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1534 		/* Set the block count to the resource fork. */
1535 		archive_le32enc(a->decmpfs_block_info++, block_count);
1536 		/* Get the position where we are going to set compressed
1537 		 * data. */
1538 		a->compressed_rsrc_position =
1539 		    RSRC_H_SIZE + 4 + (block_count * 8);
1540 		a->compressed_rsrc_position_v = a->compressed_rsrc_position;
1541 		a->decmpfs_block_count = block_count;
1542 	}
1543 
1544 	/* Ignore redundant bytes. */
1545 	if (a->file_remaining_bytes == 0)
1546 		return ((ssize_t)size);
1547 
1548 	/* Do not overrun a block size. */
1549 	if (size > a->block_remaining_bytes)
1550 		bytes_to_write = a->block_remaining_bytes;
1551 	else
1552 		bytes_to_write = size;
1553 	/* Do not overrun the file size. */
1554 	if (bytes_to_write > a->file_remaining_bytes)
1555 		bytes_to_write = a->file_remaining_bytes;
1556 
1557 	/* For efficiency, if a copy length is full of the uncompressed
1558 	 * buffer size, do not copy writing data to it. */
1559 	if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
1560 		buffer_to_write = buff;
1561 	else {
1562 		memcpy(a->uncompressed_buffer +
1563 		    MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
1564 		    buff, bytes_to_write);
1565 		buffer_to_write = a->uncompressed_buffer;
1566 	}
1567 	a->block_remaining_bytes -= bytes_to_write;
1568 	a->file_remaining_bytes -= bytes_to_write;
1569 
1570 	if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
1571 		ret = hfs_drive_compressor(a, buffer_to_write,
1572 		    MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
1573 		if (ret < 0)
1574 			return (ret);
1575 		a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1576 	}
1577 	/* Ignore redundant bytes. */
1578 	if (a->file_remaining_bytes == 0)
1579 		return ((ssize_t)size);
1580 	return (bytes_to_write);
1581 }
1582 
1583 static ssize_t
1584 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1585     size_t size)
1586 {
1587 	uint64_t start_size = size;
1588 	ssize_t bytes_written = 0;
1589 	ssize_t bytes_to_write;
1590 
1591 	if (size == 0)
1592 		return (ARCHIVE_OK);
1593 
1594 	if (a->filesize == 0 || a->fd < 0) {
1595 		archive_set_error(&a->archive, 0,
1596 		    "Attempt to write to an empty file");
1597 		return (ARCHIVE_WARN);
1598 	}
1599 
1600 	/* If this write would run beyond the file size, truncate it. */
1601 	if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
1602 		start_size = size = (size_t)(a->filesize - a->offset);
1603 
1604 	/* Write the data. */
1605 	while (size > 0) {
1606 		bytes_to_write = size;
1607 		/* Seek if necessary to the specified offset. */
1608 		if (a->offset < a->fd_offset) {
1609 			/* Can't support backward move. */
1610 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1611 			    "Seek failed");
1612 			return (ARCHIVE_FATAL);
1613 		} else if (a->offset > a->fd_offset) {
1614 			uint64_t skip = a->offset - a->fd_offset;
1615 			char nullblock[1024];
1616 
1617 			memset(nullblock, 0, sizeof(nullblock));
1618 			while (skip > 0) {
1619 				if (skip > sizeof(nullblock))
1620 					bytes_written = hfs_write_decmpfs_block(
1621 					    a, nullblock, sizeof(nullblock));
1622 				else
1623 					bytes_written = hfs_write_decmpfs_block(
1624 					    a, nullblock, skip);
1625 				if (bytes_written < 0) {
1626 					archive_set_error(&a->archive, errno,
1627 					    "Write failed");
1628 					return (ARCHIVE_WARN);
1629 				}
1630 				skip -= bytes_written;
1631 			}
1632 
1633 			a->fd_offset = a->offset;
1634 		}
1635 		bytes_written =
1636 		    hfs_write_decmpfs_block(a, buff, bytes_to_write);
1637 		if (bytes_written < 0)
1638 			return (bytes_written);
1639 		buff += bytes_written;
1640 		size -= bytes_written;
1641 		a->total_bytes_written += bytes_written;
1642 		a->offset += bytes_written;
1643 		a->fd_offset = a->offset;
1644 	}
1645 	return (start_size - size);
1646 }
1647 #else
1648 static ssize_t
1649 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1650     size_t size)
1651 {
1652 	return (write_data_block(a, buff, size));
1653 }
1654 #endif
1655 
1656 static ssize_t
1657 _archive_write_disk_data_block(struct archive *_a,
1658     const void *buff, size_t size, int64_t offset)
1659 {
1660 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1661 	ssize_t r;
1662 
1663 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1664 	    ARCHIVE_STATE_DATA, "archive_write_data_block");
1665 
1666 	a->offset = offset;
1667 	if (a->todo & TODO_HFS_COMPRESSION)
1668 		r = hfs_write_data_block(a, buff, size);
1669 	else
1670 		r = write_data_block(a, buff, size);
1671 	if (r < ARCHIVE_OK)
1672 		return (r);
1673 	if ((size_t)r < size) {
1674 		archive_set_error(&a->archive, 0,
1675 		    "Too much data: Truncating file at %ju bytes",
1676 		    (uintmax_t)a->filesize);
1677 		return (ARCHIVE_WARN);
1678 	}
1679 #if ARCHIVE_VERSION_NUMBER < 3999000
1680 	return (ARCHIVE_OK);
1681 #else
1682 	return (size);
1683 #endif
1684 }
1685 
1686 static ssize_t
1687 _archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1688 {
1689 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1690 
1691 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1692 	    ARCHIVE_STATE_DATA, "archive_write_data");
1693 
1694 	if (a->todo & TODO_HFS_COMPRESSION)
1695 		return (hfs_write_data_block(a, buff, size));
1696 	return (write_data_block(a, buff, size));
1697 }
1698 
1699 static int
1700 _archive_write_disk_finish_entry(struct archive *_a)
1701 {
1702 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1703 	int ret = ARCHIVE_OK;
1704 
1705 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1706 	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1707 	    "archive_write_finish_entry");
1708 	if (a->archive.state & ARCHIVE_STATE_HEADER)
1709 		return (ARCHIVE_OK);
1710 	archive_clear_error(&a->archive);
1711 
1712 	/* Pad or truncate file to the right size. */
1713 	if (a->fd < 0) {
1714 		/* There's no file. */
1715 	} else if (a->filesize < 0) {
1716 		/* File size is unknown, so we can't set the size. */
1717 	} else if (a->fd_offset == a->filesize) {
1718 		/* Last write ended at exactly the filesize; we're done. */
1719 		/* Hopefully, this is the common case. */
1720 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
1721 	} else if (a->todo & TODO_HFS_COMPRESSION) {
1722 		char null_d[1024];
1723 		ssize_t r;
1724 
1725 		if (a->file_remaining_bytes)
1726 			memset(null_d, 0, sizeof(null_d));
1727 		while (a->file_remaining_bytes) {
1728 			if (a->file_remaining_bytes > sizeof(null_d))
1729 				r = hfs_write_data_block(
1730 				    a, null_d, sizeof(null_d));
1731 			else
1732 				r = hfs_write_data_block(
1733 				    a, null_d, a->file_remaining_bytes);
1734 			if (r < 0) {
1735 				close_file_descriptor(a);
1736 				return ((int)r);
1737 			}
1738 		}
1739 #endif
1740 	} else {
1741 #if HAVE_FTRUNCATE
1742 		if (ftruncate(a->fd, a->filesize) == -1 &&
1743 		    a->filesize == 0) {
1744 			archive_set_error(&a->archive, errno,
1745 			    "File size could not be restored");
1746 			close_file_descriptor(a);
1747 			return (ARCHIVE_FAILED);
1748 		}
1749 #endif
1750 		/*
1751 		 * Not all platforms implement the XSI option to
1752 		 * extend files via ftruncate.  Stat() the file again
1753 		 * to see what happened.
1754 		 */
1755 		a->pst = NULL;
1756         if ((ret = lazy_stat(a)) != ARCHIVE_OK) {
1757             close_file_descriptor(a);
1758             return (ret);
1759         }
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 				close_file_descriptor(a);
1768 				return (ARCHIVE_FATAL);
1769 			}
1770 			if (write(a->fd, &nul, 1) < 0) {
1771 				archive_set_error(&a->archive, errno,
1772 				    "Write to restore size failed");
1773 				close_file_descriptor(a);
1774 				return (ARCHIVE_FATAL);
1775 			}
1776 			a->pst = NULL;
1777 		}
1778 	}
1779 
1780 	/* Restore metadata. */
1781 
1782 	/*
1783 	 * This is specific to Mac OS X.
1784 	 * If the current file is an AppleDouble file, it should be
1785 	 * linked with the data fork file and remove it.
1786 	 */
1787 	if (a->todo & TODO_APPLEDOUBLE) {
1788 		int r2 = fixup_appledouble(a, a->name);
1789 		if (r2 == ARCHIVE_EOF) {
1790 			/* The current file has been successfully linked
1791 			 * with the data fork file and removed. So there
1792 			 * is nothing to do on the current file.  */
1793 			goto finish_metadata;
1794 		}
1795 		if (r2 < ret) ret = r2;
1796 	}
1797 
1798 	/*
1799 	 * Look up the "real" UID only if we're going to need it.
1800 	 * TODO: the TODO_SGID condition can be dropped here, can't it?
1801 	 */
1802 	if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
1803 		a->uid = archive_write_disk_uid(&a->archive,
1804 		    archive_entry_uname(a->entry),
1805 		    archive_entry_uid(a->entry));
1806 	}
1807 	/* Look up the "real" GID only if we're going to need it. */
1808 	/* TODO: the TODO_SUID condition can be dropped here, can't it? */
1809 	if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
1810 		a->gid = archive_write_disk_gid(&a->archive,
1811 		    archive_entry_gname(a->entry),
1812 		    archive_entry_gid(a->entry));
1813 	 }
1814 
1815 	/*
1816 	 * Restore ownership before set_mode tries to restore suid/sgid
1817 	 * bits.  If we set the owner, we know what it is and can skip
1818 	 * a stat() call to examine the ownership of the file on disk.
1819 	 */
1820 	if (a->todo & TODO_OWNER) {
1821 		int r2 = set_ownership(a);
1822 		if (r2 < ret) ret = r2;
1823 	}
1824 
1825 	/*
1826 	 * HYPOTHESIS:
1827 	 * If we're not root, we won't be setting any security
1828 	 * attributes that may be wiped by the set_mode() routine
1829 	 * below.  We also can't set xattr on non-owner-writable files,
1830 	 * which may be the state after set_mode(). Perform
1831 	 * set_xattrs() first based on these constraints.
1832 	 */
1833 	if (a->user_uid != 0 &&
1834 	    (a->todo & TODO_XATTR)) {
1835 		int r2 = set_xattrs(a);
1836 		if (r2 < ret) ret = r2;
1837 	}
1838 
1839 	/*
1840 	 * set_mode must precede ACLs on systems such as Solaris and
1841 	 * FreeBSD where setting the mode implicitly clears extended ACLs
1842 	 */
1843 	if (a->todo & TODO_MODE) {
1844 		int r2 = set_mode(a, a->mode);
1845 		if (r2 < ret) ret = r2;
1846 	}
1847 
1848 	/*
1849 	 * Security-related extended attributes (such as
1850 	 * security.capability on Linux) have to be restored last,
1851 	 * since they're implicitly removed by other file changes.
1852 	 * We do this last only when root.
1853 	 */
1854 	if (a->user_uid == 0 &&
1855 	    (a->todo & TODO_XATTR)) {
1856 		int r2 = set_xattrs(a);
1857 		if (r2 < ret) ret = r2;
1858 	}
1859 
1860 	/*
1861 	 * Some flags prevent file modification; they must be restored after
1862 	 * file contents are written.
1863 	 */
1864 	if (a->todo & TODO_FFLAGS) {
1865 		int r2 = set_fflags(a);
1866 		if (r2 < ret) ret = r2;
1867 	}
1868 
1869 	/*
1870 	 * Time must follow most other metadata;
1871 	 * otherwise atime will get changed.
1872 	 */
1873 	if (a->todo & TODO_TIMES) {
1874 		int r2 = set_times_from_entry(a);
1875 		if (r2 < ret) ret = r2;
1876 	}
1877 
1878 	/*
1879 	 * Mac extended metadata includes ACLs.
1880 	 */
1881 	if (a->todo & TODO_MAC_METADATA) {
1882 		const void *metadata;
1883 		size_t metadata_size;
1884 		metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
1885 		if (metadata != NULL && metadata_size > 0) {
1886 			int r2 = set_mac_metadata(a, archive_entry_pathname(
1887 			    a->entry), metadata, metadata_size);
1888 			if (r2 < ret) ret = r2;
1889 		}
1890 	}
1891 
1892 	/*
1893 	 * ACLs must be restored after timestamps because there are
1894 	 * ACLs that prevent attribute changes (including time).
1895 	 */
1896 	if (a->todo & TODO_ACLS) {
1897 		int r2;
1898 		r2 = archive_write_disk_set_acls(&a->archive, a->fd,
1899 		    archive_entry_pathname(a->entry),
1900 		    archive_entry_acl(a->entry),
1901 		    archive_entry_mode(a->entry));
1902 		if (r2 < ret) ret = r2;
1903 	}
1904 
1905 finish_metadata:
1906 	/* If there's an fd, we can close it now. */
1907 	if (a->fd >= 0) {
1908 		close(a->fd);
1909 		a->fd = -1;
1910 		if (a->tmpname) {
1911 			if (rename(a->tmpname, a->name) == -1) {
1912 				archive_set_error(&a->archive, errno,
1913 				    "Failed to rename temporary file");
1914 				ret = ARCHIVE_FAILED;
1915 				unlink(a->tmpname);
1916 			}
1917 			a->tmpname = NULL;
1918 		}
1919 	}
1920 	/* If there's an entry, we can release it now. */
1921 	archive_entry_free(a->entry);
1922 	a->entry = NULL;
1923 	a->archive.state = ARCHIVE_STATE_HEADER;
1924 	return (ret);
1925 }
1926 
1927 int
1928 archive_write_disk_set_group_lookup(struct archive *_a,
1929     void *private_data,
1930     la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1931     void (*cleanup_gid)(void *private))
1932 {
1933 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1934 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1935 	    ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
1936 
1937 	if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1938 		(a->cleanup_gid)(a->lookup_gid_data);
1939 
1940 	a->lookup_gid = lookup_gid;
1941 	a->cleanup_gid = cleanup_gid;
1942 	a->lookup_gid_data = private_data;
1943 	return (ARCHIVE_OK);
1944 }
1945 
1946 int
1947 archive_write_disk_set_user_lookup(struct archive *_a,
1948     void *private_data,
1949     int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1950     void (*cleanup_uid)(void *private))
1951 {
1952 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1953 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1954 	    ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
1955 
1956 	if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1957 		(a->cleanup_uid)(a->lookup_uid_data);
1958 
1959 	a->lookup_uid = lookup_uid;
1960 	a->cleanup_uid = cleanup_uid;
1961 	a->lookup_uid_data = private_data;
1962 	return (ARCHIVE_OK);
1963 }
1964 
1965 int64_t
1966 archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1967 {
1968        struct archive_write_disk *a = (struct archive_write_disk *)_a;
1969        archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1970            ARCHIVE_STATE_ANY, "archive_write_disk_gid");
1971        if (a->lookup_gid)
1972                return (a->lookup_gid)(a->lookup_gid_data, name, id);
1973        return (id);
1974 }
1975 
1976 int64_t
1977 archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1978 {
1979 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1980 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1981 	    ARCHIVE_STATE_ANY, "archive_write_disk_uid");
1982 	if (a->lookup_uid)
1983 		return (a->lookup_uid)(a->lookup_uid_data, name, id);
1984 	return (id);
1985 }
1986 
1987 /*
1988  * Create a new archive_write_disk object and initialize it with global state.
1989  */
1990 struct archive *
1991 archive_write_disk_new(void)
1992 {
1993 	struct archive_write_disk *a;
1994 
1995 	a = (struct archive_write_disk *)calloc(1, sizeof(*a));
1996 	if (a == NULL)
1997 		return (NULL);
1998 	a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
1999 	/* We're ready to write a header immediately. */
2000 	a->archive.state = ARCHIVE_STATE_HEADER;
2001 	a->archive.vtable = &archive_write_disk_vtable;
2002 	a->start_time = time(NULL);
2003 	/* Query and restore the umask. */
2004 	umask(a->user_umask = umask(0));
2005 #ifdef HAVE_GETEUID
2006 	a->user_uid = geteuid();
2007 #endif /* HAVE_GETEUID */
2008 	if (archive_string_ensure(&a->path_safe, 512) == NULL) {
2009 		free(a);
2010 		return (NULL);
2011 	}
2012 	a->path_safe.s[0] = 0;
2013 
2014 #ifdef HAVE_ZLIB_H
2015 	a->decmpfs_compression_level = 5;
2016 #endif
2017 	return (&a->archive);
2018 }
2019 
2020 
2021 /*
2022  * If pathname is longer than PATH_MAX, chdir to a suitable
2023  * intermediate dir and edit the path down to a shorter suffix.  Note
2024  * that this routine never returns an error; if the chdir() attempt
2025  * fails for any reason, we just go ahead with the long pathname.  The
2026  * object creation is likely to fail, but any error will get handled
2027  * at that time.
2028  */
2029 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
2030 static void
2031 edit_deep_directories(struct archive_write_disk *a)
2032 {
2033 	int ret;
2034 	char *tail = a->name;
2035 
2036 	/* If path is short, avoid the open() below. */
2037 	if (strlen(tail) < PATH_MAX)
2038 		return;
2039 
2040 	/* Try to record our starting dir. */
2041 	a->restore_pwd = la_opendirat(AT_FDCWD, ".");
2042 	__archive_ensure_cloexec_flag(a->restore_pwd);
2043 	if (a->restore_pwd < 0)
2044 		return;
2045 
2046 	/* As long as the path is too long... */
2047 	while (strlen(tail) >= PATH_MAX) {
2048 		/* Locate a dir prefix shorter than PATH_MAX. */
2049 		tail += PATH_MAX - 8;
2050 		while (tail > a->name && *tail != '/')
2051 			tail--;
2052 		/* Exit if we find a too-long path component. */
2053 		if (tail <= a->name)
2054 			return;
2055 		/* Create the intermediate dir and chdir to it. */
2056 		*tail = '\0'; /* Terminate dir portion */
2057 		ret = create_dir(a, a->name);
2058 		if (ret == ARCHIVE_OK && chdir(a->name) != 0)
2059 			ret = ARCHIVE_FAILED;
2060 		*tail = '/'; /* Restore the / we removed. */
2061 		if (ret != ARCHIVE_OK)
2062 			return;
2063 		tail++;
2064 		/* The chdir() succeeded; we've now shortened the path. */
2065 		a->name = tail;
2066 	}
2067 	return;
2068 }
2069 #endif
2070 
2071 /*
2072  * The main restore function.
2073  */
2074 static int
2075 restore_entry(struct archive_write_disk *a)
2076 {
2077 	int ret = ARCHIVE_OK, en;
2078 
2079 	if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
2080 		/*
2081 		 * TODO: Fix this.  Apparently, there are platforms
2082 		 * that still allow root to hose the entire filesystem
2083 		 * by unlinking a dir.  The S_ISDIR() test above
2084 		 * prevents us from using unlink() here if the new
2085 		 * object is a dir, but that doesn't mean the old
2086 		 * object isn't a dir.
2087 		 */
2088 		if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2089 			(void)clear_nochange_fflags(a);
2090 		if (unlink(a->name) == 0) {
2091 			/* We removed it, reset cached stat. */
2092 			a->pst = NULL;
2093 		} else if (errno == ENOENT) {
2094 			/* File didn't exist, that's just as good. */
2095 		} else if (rmdir(a->name) == 0) {
2096 			/* It was a dir, but now it's gone. */
2097 			a->pst = NULL;
2098 		} else {
2099 			/* We tried, but couldn't get rid of it. */
2100 			archive_set_error(&a->archive, errno,
2101 			    "Could not unlink");
2102 			return(ARCHIVE_FAILED);
2103 		}
2104 	}
2105 
2106 	/* Try creating it first; if this fails, we'll try to recover. */
2107 	en = create_filesystem_object(a);
2108 
2109 	if ((en == ENOTDIR || en == ENOENT)
2110 	    && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
2111 		/* If the parent dir doesn't exist, try creating it. */
2112 		create_parent_dir(a, a->name);
2113 		/* Now try to create the object again. */
2114 		en = create_filesystem_object(a);
2115 	}
2116 
2117 	if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
2118 		archive_set_error(&a->archive, en,
2119 		    "Hard-link target '%s' does not exist.",
2120 		    archive_entry_hardlink(a->entry));
2121 		return (ARCHIVE_FAILED);
2122 	}
2123 
2124 	if ((en == EISDIR || en == EEXIST)
2125 	    && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2126 		/* If we're not overwriting, we're done. */
2127 		if (S_ISDIR(a->mode)) {
2128 			/* Don't overwrite any settings on existing directories. */
2129 			a->todo = 0;
2130 		}
2131 		archive_entry_unset_size(a->entry);
2132 		return (ARCHIVE_OK);
2133 	}
2134 
2135 	/*
2136 	 * Some platforms return EISDIR if you call
2137 	 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
2138 	 * return EEXIST.  POSIX is ambiguous, requiring EISDIR
2139 	 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
2140 	 * on an existing item.
2141 	 */
2142 	if (en == EISDIR) {
2143 		/* A dir is in the way of a non-dir, rmdir it. */
2144 		if (rmdir(a->name) != 0) {
2145 			archive_set_error(&a->archive, errno,
2146 			    "Can't remove already-existing dir");
2147 			return (ARCHIVE_FAILED);
2148 		}
2149 		a->pst = NULL;
2150 		/* Try again. */
2151 		en = create_filesystem_object(a);
2152 	} else if (en == EEXIST) {
2153 		/*
2154 		 * We know something is in the way, but we don't know what;
2155 		 * we need to find out before we go any further.
2156 		 */
2157 		int r = 0;
2158 		/*
2159 		 * The SECURE_SYMLINKS logic has already removed a
2160 		 * symlink to a dir if the client wants that.  So
2161 		 * follow the symlink if we're creating a dir.
2162 		 */
2163 		if (S_ISDIR(a->mode))
2164 			r = la_stat(a->name, &a->st);
2165 		/*
2166 		 * If it's not a dir (or it's a broken symlink),
2167 		 * then don't follow it.
2168 		 */
2169 		if (r != 0 || !S_ISDIR(a->mode))
2170 #ifdef HAVE_LSTAT
2171 			r = lstat(a->name, &a->st);
2172 #else
2173 			r = la_stat(a->name, &a->st);
2174 #endif
2175 		if (r != 0) {
2176 			archive_set_error(&a->archive, errno,
2177 			    "Can't stat existing object");
2178 			return (ARCHIVE_FAILED);
2179 		}
2180 
2181 		/*
2182 		 * NO_OVERWRITE_NEWER doesn't apply to directories.
2183 		 */
2184 		if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
2185 		    &&  !S_ISDIR(a->st.st_mode)) {
2186 			if (!older(&(a->st), a->entry)) {
2187 				archive_entry_unset_size(a->entry);
2188 				return (ARCHIVE_OK);
2189 			}
2190 		}
2191 
2192 		/* If it's our archive, we're done. */
2193 		if (a->skip_file_set &&
2194 		    a->st.st_dev == (dev_t)a->skip_file_dev &&
2195 		    a->st.st_ino == (ino_t)a->skip_file_ino) {
2196 			archive_set_error(&a->archive, 0,
2197 			    "Refusing to overwrite archive");
2198 			return (ARCHIVE_FAILED);
2199 		}
2200 
2201 		if (!S_ISDIR(a->st.st_mode)) {
2202 			if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2203 				(void)clear_nochange_fflags(a);
2204 
2205 			if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) &&
2206 			    S_ISREG(a->st.st_mode)) {
2207 				/* Use a temporary file to extract */
2208 				if ((a->fd = la_mktemp(a)) == -1) {
2209 					archive_set_error(&a->archive, errno,
2210 					    "Can't create temporary file");
2211 					return ARCHIVE_FAILED;
2212 				}
2213 				a->pst = NULL;
2214 				en = 0;
2215 			} else {
2216 				/* A non-dir is in the way, unlink it. */
2217 				if (unlink(a->name) != 0) {
2218 					archive_set_error(&a->archive, errno,
2219 					    "Can't unlink already-existing "
2220 					    "object");
2221 					return (ARCHIVE_FAILED);
2222 				}
2223 				a->pst = NULL;
2224 				/* Try again. */
2225 				en = create_filesystem_object(a);
2226 			}
2227 		} else if (!S_ISDIR(a->mode)) {
2228 			/* A dir is in the way of a non-dir, rmdir it. */
2229 			if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2230 				(void)clear_nochange_fflags(a);
2231 			if (rmdir(a->name) != 0) {
2232 				archive_set_error(&a->archive, errno,
2233 				    "Can't replace existing directory with non-directory");
2234 				return (ARCHIVE_FAILED);
2235 			}
2236 			/* Try again. */
2237 			en = create_filesystem_object(a);
2238 		} else {
2239 			/*
2240 			 * There's a dir in the way of a dir.  Don't
2241 			 * waste time with rmdir()/mkdir(), just fix
2242 			 * up the permissions on the existing dir.
2243 			 * Note that we don't change perms on existing
2244 			 * dirs unless _EXTRACT_PERM is specified.
2245 			 */
2246 			if ((a->mode != a->st.st_mode)
2247 			    && (a->todo & TODO_MODE_FORCE))
2248 				a->deferred |= (a->todo & TODO_MODE);
2249 			/* Ownership doesn't need deferred fixup. */
2250 			en = 0; /* Forget the EEXIST. */
2251 		}
2252 	}
2253 
2254 	if (en) {
2255 		/* Everything failed; give up here. */
2256 		if ((&a->archive)->error == NULL)
2257 			archive_set_error(&a->archive, en, "Can't create '%s'",
2258 			    a->name);
2259 		return (ARCHIVE_FAILED);
2260 	}
2261 
2262 	a->pst = NULL; /* Cached stat data no longer valid. */
2263 	return (ret);
2264 }
2265 
2266 /*
2267  * Returns 0 if creation succeeds, or else returns errno value from
2268  * the failed system call.   Note:  This function should only ever perform
2269  * a single system call.
2270  */
2271 static int
2272 create_filesystem_object(struct archive_write_disk *a)
2273 {
2274 	/* Create the entry. */
2275 	const char *linkname;
2276 	mode_t final_mode, mode;
2277 	int r;
2278 	/* these for check_symlinks_fsobj */
2279 	char *linkname_copy;	/* non-const copy of linkname */
2280 	struct stat st;
2281 	struct archive_string error_string;
2282 	int error_number;
2283 
2284 	/* We identify hard/symlinks according to the link names. */
2285 	/* Since link(2) and symlink(2) don't handle modes, we're done here. */
2286 	linkname = archive_entry_hardlink(a->entry);
2287 	if (linkname != NULL) {
2288 #if !HAVE_LINK
2289 		return (EPERM);
2290 #else
2291 		archive_string_init(&error_string);
2292 		linkname_copy = strdup(linkname);
2293 		if (linkname_copy == NULL) {
2294 		    return (EPERM);
2295 		}
2296 		/*
2297 		 * TODO: consider using the cleaned-up path as the link
2298 		 * target?
2299 		 */
2300 		r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2301 		    &error_string, a->flags);
2302 		if (r != ARCHIVE_OK) {
2303 			archive_set_error(&a->archive, error_number, "%s",
2304 			    error_string.s);
2305 			free(linkname_copy);
2306 			archive_string_free(&error_string);
2307 			/*
2308 			 * EPERM is more appropriate than error_number for our
2309 			 * callers
2310 			 */
2311 			return (EPERM);
2312 		}
2313 		r = check_symlinks_fsobj(linkname_copy, &error_number,
2314 		    &error_string, a->flags, 1);
2315 		if (r != ARCHIVE_OK) {
2316 			archive_set_error(&a->archive, error_number, "%s",
2317 			    error_string.s);
2318 			free(linkname_copy);
2319 			archive_string_free(&error_string);
2320 			/*
2321 			 * EPERM is more appropriate than error_number for our
2322 			 * callers
2323 			 */
2324 			return (EPERM);
2325 		}
2326 		free(linkname_copy);
2327 		archive_string_free(&error_string);
2328 		/*
2329 		 * Unlinking and linking here is really not atomic,
2330 		 * but doing it right, would require us to construct
2331 		 * an mktemplink() function, and then use rename(2).
2332 		 */
2333 		if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2334 			unlink(a->name);
2335 #ifdef HAVE_LINKAT
2336 		r = linkat(AT_FDCWD, linkname, AT_FDCWD, a->name,
2337 		    0) ? errno : 0;
2338 #else
2339 		r = link(linkname, a->name) ? errno : 0;
2340 #endif
2341 		/*
2342 		 * New cpio and pax formats allow hardlink entries
2343 		 * to carry data, so we may have to open the file
2344 		 * for hardlink entries.
2345 		 *
2346 		 * If the hardlink was successfully created and
2347 		 * the archive doesn't have carry data for it,
2348 		 * consider it to be non-authoritative for meta data.
2349 		 * This is consistent with GNU tar and BSD pax.
2350 		 * If the hardlink does carry data, let the last
2351 		 * archive entry decide ownership.
2352 		 */
2353 		if (r == 0 && a->filesize <= 0) {
2354 			a->todo = 0;
2355 			a->deferred = 0;
2356 		} else if (r == 0 && a->filesize > 0) {
2357 #ifdef HAVE_LSTAT
2358 			r = lstat(a->name, &st);
2359 #else
2360 			r = la_stat(a->name, &st);
2361 #endif
2362 			if (r != 0)
2363 				r = errno;
2364 			else if ((st.st_mode & AE_IFMT) == AE_IFREG) {
2365 				a->fd = open(a->name, O_WRONLY | O_TRUNC |
2366 				    O_BINARY | O_CLOEXEC | O_NOFOLLOW);
2367 				__archive_ensure_cloexec_flag(a->fd);
2368 				if (a->fd < 0)
2369 					r = errno;
2370 			}
2371 		}
2372 		return (r);
2373 #endif
2374 	}
2375 	linkname = archive_entry_symlink(a->entry);
2376 	if (linkname != NULL) {
2377 #if HAVE_SYMLINK
2378 		/*
2379 		 * Unlinking and linking here is really not atomic,
2380 		 * but doing it right, would require us to construct
2381 		 * an mktempsymlink() function, and then use rename(2).
2382 		 */
2383 		if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2384 			unlink(a->name);
2385 		return symlink(linkname, a->name) ? errno : 0;
2386 #else
2387 		return (EPERM);
2388 #endif
2389 	}
2390 
2391 	/*
2392 	 * The remaining system calls all set permissions, so let's
2393 	 * try to take advantage of that to avoid an extra chmod()
2394 	 * call.  (Recall that umask is set to zero right now!)
2395 	 */
2396 
2397 	/* Mode we want for the final restored object (w/o file type bits). */
2398 	final_mode = a->mode & 07777;
2399 	/*
2400 	 * The mode that will actually be restored in this step.  Note
2401 	 * that SUID, SGID, etc, require additional work to ensure
2402 	 * security, so we never restore them at this point.
2403 	 */
2404 	mode = final_mode & 0777 & ~a->user_umask;
2405 
2406 	/*
2407 	 * Always create writable such that [f]setxattr() works if we're not
2408 	 * root.
2409 	 */
2410 	if (a->user_uid != 0 &&
2411 	    a->todo & (TODO_HFS_COMPRESSION | TODO_XATTR)) {
2412 		mode |= 0200;
2413 	}
2414 
2415 	switch (a->mode & AE_IFMT) {
2416 	default:
2417 		/* POSIX requires that we fall through here. */
2418 		/* FALLTHROUGH */
2419 	case AE_IFREG:
2420 		a->tmpname = NULL;
2421 		a->fd = open(a->name,
2422 		    O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2423 		__archive_ensure_cloexec_flag(a->fd);
2424 		r = (a->fd < 0);
2425 		break;
2426 	case AE_IFCHR:
2427 #ifdef HAVE_MKNOD
2428 		/* Note: we use AE_IFCHR for the case label, and
2429 		 * S_IFCHR for the mknod() call.  This is correct.  */
2430 		r = mknod(a->name, mode | S_IFCHR,
2431 		    archive_entry_rdev(a->entry));
2432 		break;
2433 #else
2434 		/* TODO: Find a better way to warn about our inability
2435 		 * to restore a char device node. */
2436 		return (EINVAL);
2437 #endif /* HAVE_MKNOD */
2438 	case AE_IFBLK:
2439 #ifdef HAVE_MKNOD
2440 		r = mknod(a->name, mode | S_IFBLK,
2441 		    archive_entry_rdev(a->entry));
2442 		break;
2443 #else
2444 		/* TODO: Find a better way to warn about our inability
2445 		 * to restore a block device node. */
2446 		return (EINVAL);
2447 #endif /* HAVE_MKNOD */
2448 	case AE_IFDIR:
2449 		mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2450 		r = mkdir(a->name, mode);
2451 		if (r == 0) {
2452 			/* Defer setting dir times. */
2453 			a->deferred |= (a->todo & TODO_TIMES);
2454 			a->todo &= ~TODO_TIMES;
2455 			/* Never use an immediate chmod(). */
2456 			/* We can't avoid the chmod() entirely if EXTRACT_PERM
2457 			 * because of SysV SGID inheritance. */
2458 			if ((mode != final_mode)
2459 			    || (a->flags & ARCHIVE_EXTRACT_PERM))
2460 				a->deferred |= (a->todo & TODO_MODE);
2461 			a->todo &= ~TODO_MODE;
2462 		}
2463 		break;
2464 	case AE_IFIFO:
2465 #ifdef HAVE_MKFIFO
2466 		r = mkfifo(a->name, mode);
2467 		break;
2468 #else
2469 		/* TODO: Find a better way to warn about our inability
2470 		 * to restore a fifo. */
2471 		return (EINVAL);
2472 #endif /* HAVE_MKFIFO */
2473 	}
2474 
2475 	/* All the system calls above set errno on failure. */
2476 	if (r)
2477 		return (errno);
2478 
2479 	/* If we managed to set the final mode, we've avoided a chmod(). */
2480 	if (mode == final_mode)
2481 		a->todo &= ~TODO_MODE;
2482 	return (0);
2483 }
2484 
2485 /*
2486  * Cleanup function for archive_extract.  Mostly, this involves processing
2487  * the fixup list, which is used to address a number of problems:
2488  *   * Dir permissions might prevent us from restoring a file in that
2489  *     dir, so we restore the dir with minimum 0700 permissions first,
2490  *     then correct the mode at the end.
2491  *   * Similarly, the act of restoring a file touches the directory
2492  *     and changes the timestamp on the dir, so we have to touch-up dir
2493  *     timestamps at the end as well.
2494  *   * Some file flags can interfere with the restore by, for example,
2495  *     preventing the creation of hardlinks to those files.
2496  *   * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2497  *
2498  * Note that tar/cpio do not require that archives be in a particular
2499  * order; there is no way to know when the last file has been restored
2500  * within a directory, so there's no way to optimize the memory usage
2501  * here by fixing up the directory any earlier than the
2502  * end-of-archive.
2503  *
2504  * XXX TODO: Directory ACLs should be restored here, for the same
2505  * reason we set directory perms here. XXX
2506  */
2507 static int
2508 _archive_write_disk_close(struct archive *_a)
2509 {
2510 	struct archive_write_disk *a = (struct archive_write_disk *)_a;
2511 	struct fixup_entry *next, *p;
2512 	struct stat st;
2513 	char *c;
2514 	int fd, ret, openflags;
2515 
2516 	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2517 	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2518 	    "archive_write_disk_close");
2519 	ret = _archive_write_disk_finish_entry(&a->archive);
2520 
2521 	/* Sort dir list so directories are fixed up in depth-first order. */
2522 	p = sort_dir_list(a->fixup_list);
2523 
2524 	while (p != NULL) {
2525 		fd = -1;
2526 		a->pst = NULL; /* Mark stat cache as out-of-date. */
2527 
2528 		/* We must strip trailing slashes from the path to avoid
2529 		   dereferencing symbolic links to directories */
2530 		c = p->name;
2531 		while (*c != '\0')
2532 			c++;
2533 		while (c != p->name && *(c - 1) == '/') {
2534 			c--;
2535 			*c = '\0';
2536 		}
2537 
2538 		if (p->fixup == 0)
2539 			goto skip_fixup_entry;
2540 		else {
2541 			/*
2542 			 * We need to verify if the type of the file
2543 			 * we are going to open matches the file type
2544 			 * of the fixup entry.
2545 			 */
2546 			openflags = O_BINARY | O_NOFOLLOW | O_RDONLY
2547 			    | O_CLOEXEC;
2548 #if defined(O_DIRECTORY)
2549 			if (p->filetype == AE_IFDIR)
2550 				openflags |= O_DIRECTORY;
2551 #endif
2552 			fd = open(p->name, openflags);
2553 
2554 #if defined(O_DIRECTORY)
2555 			/*
2556 			 * If we support O_DIRECTORY and open was
2557 			 * successful we can skip the file type check
2558 			 * for directories. For other file types
2559 			 * we need to verify via fstat() or lstat()
2560 			 */
2561 			if (fd == -1 || p->filetype != AE_IFDIR) {
2562 #if HAVE_FSTAT
2563 				if (fd > 0 && (
2564 				    fstat(fd, &st) != 0 ||
2565 				    la_verify_filetype(st.st_mode,
2566 				    p->filetype) == 0)) {
2567 					goto skip_fixup_entry;
2568 				} else
2569 #endif
2570 				if (
2571 #ifdef HAVE_LSTAT
2572 					lstat(p->name, &st) != 0 ||
2573 #else
2574 					la_stat(p->name, &st) != 0 ||
2575 #endif
2576 				    la_verify_filetype(st.st_mode,
2577 				    p->filetype) == 0) {
2578 					goto skip_fixup_entry;
2579 				}
2580 			}
2581 #else
2582 #if HAVE_FSTAT
2583 			if (fd > 0 && (
2584 			    fstat(fd, &st) != 0 ||
2585 			    la_verify_filetype(st.st_mode,
2586 			    p->filetype) == 0)) {
2587 				goto skip_fixup_entry;
2588 			} else
2589 #endif
2590 			if (
2591 #ifdef HAVE_LSTAT
2592 				lstat(p->name, &st) != 0 ||
2593 #else
2594 				la_stat(p->name, &st) != 0 ||
2595 #endif
2596 			    la_verify_filetype(st.st_mode,
2597 			    p->filetype) == 0) {
2598 				goto skip_fixup_entry;
2599 			}
2600 #endif
2601 		}
2602 		if (p->fixup & TODO_TIMES) {
2603 			set_times(a, fd, p->mode, p->name,
2604 			    p->atime, p->atime_nanos,
2605 			    p->birthtime, p->birthtime_nanos,
2606 			    p->mtime, p->mtime_nanos,
2607 			    p->ctime, p->ctime_nanos);
2608 		}
2609 		if (p->fixup & TODO_MODE_BASE) {
2610 #ifdef HAVE_FCHMOD
2611 			if (fd >= 0)
2612 				fchmod(fd, p->mode & 07777);
2613 			else
2614 #endif
2615 #ifdef HAVE_LCHMOD
2616 			lchmod(p->name, p->mode & 07777);
2617 #else
2618 			chmod(p->name, p->mode & 07777);
2619 #endif
2620 		}
2621 		if (p->fixup & TODO_ACLS)
2622 			archive_write_disk_set_acls(&a->archive, fd,
2623 			    p->name, &p->acl, p->mode);
2624 		if (p->fixup & TODO_FFLAGS)
2625 			set_fflags_platform(a, fd, p->name,
2626 			    p->mode, p->fflags_set, 0);
2627 		if (p->fixup & TODO_MAC_METADATA)
2628 			set_mac_metadata(a, p->name, p->mac_metadata,
2629 					 p->mac_metadata_size);
2630 skip_fixup_entry:
2631 		next = p->next;
2632 		archive_acl_clear(&p->acl);
2633 		free(p->mac_metadata);
2634 		free(p->name);
2635 		if (fd >= 0)
2636 			close(fd);
2637 		free(p);
2638 		p = next;
2639 	}
2640 	a->fixup_list = NULL;
2641 	return (ret);
2642 }
2643 
2644 static int
2645 _archive_write_disk_free(struct archive *_a)
2646 {
2647 	struct archive_write_disk *a;
2648 	int ret;
2649 	if (_a == NULL)
2650 		return (ARCHIVE_OK);
2651 	archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2652 	    ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2653 	a = (struct archive_write_disk *)_a;
2654 	ret = _archive_write_disk_close(&a->archive);
2655 	archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2656 	archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2657 	archive_entry_free(a->entry);
2658 	archive_string_free(&a->_name_data);
2659 	archive_string_free(&a->_tmpname_data);
2660 	archive_string_free(&a->archive.error_string);
2661 	archive_string_free(&a->path_safe);
2662 	a->archive.magic = 0;
2663 	__archive_clean(&a->archive);
2664 	free(a->decmpfs_header_p);
2665 	free(a->resource_fork);
2666 	free(a->compressed_buffer);
2667 	free(a->uncompressed_buffer);
2668 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2669 	&& defined(HAVE_ZLIB_H)
2670 	if (a->stream_valid) {
2671 		switch (deflateEnd(&a->stream)) {
2672 		case Z_OK:
2673 			break;
2674 		default:
2675 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2676 			    "Failed to clean up compressor");
2677 			ret = ARCHIVE_FATAL;
2678 			break;
2679 		}
2680 	}
2681 #endif
2682 	free(a);
2683 	return (ret);
2684 }
2685 
2686 /*
2687  * Simple O(n log n) merge sort to order the fixup list.  In
2688  * particular, we want to restore dir timestamps depth-first.
2689  */
2690 static struct fixup_entry *
2691 sort_dir_list(struct fixup_entry *p)
2692 {
2693 	struct fixup_entry *a, *b, *t;
2694 
2695 	if (p == NULL)
2696 		return (NULL);
2697 	/* A one-item list is already sorted. */
2698 	if (p->next == NULL)
2699 		return (p);
2700 
2701 	/* Step 1: split the list. */
2702 	t = p;
2703 	a = p->next->next;
2704 	while (a != NULL) {
2705 		/* Step a twice, t once. */
2706 		a = a->next;
2707 		if (a != NULL)
2708 			a = a->next;
2709 		t = t->next;
2710 	}
2711 	/* Now, t is at the mid-point, so break the list here. */
2712 	b = t->next;
2713 	t->next = NULL;
2714 	a = p;
2715 
2716 	/* Step 2: Recursively sort the two sub-lists. */
2717 	a = sort_dir_list(a);
2718 	b = sort_dir_list(b);
2719 
2720 	/* Step 3: Merge the returned lists. */
2721 	/* Pick the first element for the merged list. */
2722 	if (strcmp(a->name, b->name) > 0) {
2723 		t = p = a;
2724 		a = a->next;
2725 	} else {
2726 		t = p = b;
2727 		b = b->next;
2728 	}
2729 
2730 	/* Always put the later element on the list first. */
2731 	while (a != NULL && b != NULL) {
2732 		if (strcmp(a->name, b->name) > 0) {
2733 			t->next = a;
2734 			a = a->next;
2735 		} else {
2736 			t->next = b;
2737 			b = b->next;
2738 		}
2739 		t = t->next;
2740 	}
2741 
2742 	/* Only one list is non-empty, so just splice it on. */
2743 	if (a != NULL)
2744 		t->next = a;
2745 	if (b != NULL)
2746 		t->next = b;
2747 
2748 	return (p);
2749 }
2750 
2751 /*
2752  * Returns a new, initialized fixup entry.
2753  *
2754  * TODO: Reduce the memory requirements for this list by using a tree
2755  * structure rather than a simple list of names.
2756  */
2757 static struct fixup_entry *
2758 new_fixup(struct archive_write_disk *a, const char *pathname)
2759 {
2760 	struct fixup_entry *fe;
2761 
2762 	fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2763 	if (fe == NULL) {
2764 		archive_set_error(&a->archive, ENOMEM,
2765 		    "Can't allocate memory for a fixup");
2766 		return (NULL);
2767 	}
2768 	fe->next = a->fixup_list;
2769 	a->fixup_list = fe;
2770 	fe->fixup = 0;
2771 	fe->filetype = 0;
2772 	fe->name = strdup(pathname);
2773 	return (fe);
2774 }
2775 
2776 /*
2777  * Returns a fixup structure for the current entry.
2778  */
2779 static struct fixup_entry *
2780 current_fixup(struct archive_write_disk *a, const char *pathname)
2781 {
2782 	if (a->current_fixup == NULL)
2783 		a->current_fixup = new_fixup(a, pathname);
2784 	return (a->current_fixup);
2785 }
2786 
2787 /* Error helper for new *_fsobj functions */
2788 static void
2789 fsobj_error(int *a_eno, struct archive_string *a_estr,
2790     int err, const char *errstr, const char *path)
2791 {
2792 	if (a_eno)
2793 		*a_eno = err;
2794 	if (a_estr)
2795 		archive_string_sprintf(a_estr, "%s%s", errstr, path);
2796 }
2797 
2798 /*
2799  * TODO: Someday, integrate this with the deep dir support; they both
2800  * scan the path and both can be optimized by comparing against other
2801  * recent paths.
2802  */
2803 /*
2804  * Checks the given path to see if any elements along it are symlinks.  Returns
2805  * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2806  */
2807 static int
2808 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2809     int flags, int checking_linkname)
2810 {
2811 #if !defined(HAVE_LSTAT) && \
2812     !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT))
2813 	/* Platform doesn't have lstat, so we can't look for symlinks. */
2814 	(void)path; /* UNUSED */
2815 	(void)a_eno; /* UNUSED */
2816 	(void)a_estr; /* UNUSED */
2817 	(void)flags; /* UNUSED */
2818 	(void)checking_linkname; /* UNUSED */
2819 	return (ARCHIVE_OK);
2820 #else
2821 	int res = ARCHIVE_OK;
2822 	char *tail;
2823 	char *head;
2824 	int last;
2825 	char c = '\0';
2826 	int r;
2827 	struct stat st;
2828 	int chdir_fd;
2829 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2830 	int fd;
2831 #endif
2832 
2833 	/* Nothing to do here if name is empty */
2834 	if(path[0] == '\0')
2835 	    return (ARCHIVE_OK);
2836 
2837 	/*
2838 	 * Guard against symlink tricks.  Reject any archive entry whose
2839 	 * destination would be altered by a symlink.
2840 	 *
2841 	 * Walk the filename in chunks separated by '/'.  For each segment:
2842 	 *  - if it doesn't exist, continue
2843 	 *  - if it's symlink, abort or remove it
2844 	 *  - if it's a directory and it's not the last chunk, cd into it
2845 	 * As we go:
2846 	 *  head points to the current (relative) path
2847 	 *  tail points to the temporary \0 terminating the segment we're
2848 	 *      currently examining
2849 	 *  c holds what used to be in *tail
2850 	 *  last is 1 if this is the last tail
2851 	 */
2852 	chdir_fd = la_opendirat(AT_FDCWD, ".");
2853 	__archive_ensure_cloexec_flag(chdir_fd);
2854 	if (chdir_fd < 0) {
2855 		fsobj_error(a_eno, a_estr, errno,
2856 		    "Could not open ", path);
2857 		return (ARCHIVE_FATAL);
2858 	}
2859 	head = path;
2860 	tail = path;
2861 	last = 0;
2862 	/* TODO: reintroduce a safe cache here? */
2863 	/* Skip the root directory if the path is absolute. */
2864 	if(tail == path && tail[0] == '/')
2865 		++tail;
2866 	/* Keep going until we've checked the entire name.
2867 	 * head, tail, path all alias the same string, which is
2868 	 * temporarily zeroed at tail, so be careful restoring the
2869 	 * stashed (c=tail[0]) for error messages.
2870 	 * Exiting the loop with break is okay; continue is not.
2871 	 */
2872 	while (!last) {
2873 		/*
2874 		 * Skip the separator we just consumed, plus any adjacent ones
2875 		 */
2876 		while (*tail == '/')
2877 		    ++tail;
2878 		/* Skip the next path element. */
2879 		while (*tail != '\0' && *tail != '/')
2880 			++tail;
2881 		/* is this the last path component? */
2882 		last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2883 		/* temporarily truncate the string here */
2884 		c = tail[0];
2885 		tail[0] = '\0';
2886 		/* Check that we haven't hit a symlink. */
2887 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2888 		r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW);
2889 #elif defined(HAVE_LSTAT)
2890 		r = lstat(head, &st);
2891 #else
2892 		r = la_stat(head, &st);
2893 #endif
2894 		if (r != 0) {
2895 			tail[0] = c;
2896 			/* We've hit a dir that doesn't exist; stop now. */
2897 			if (errno == ENOENT) {
2898 				break;
2899 			} else {
2900 				/*
2901 				 * Treat any other error as fatal - best to be
2902 				 * paranoid here.
2903 				 * Note: This effectively disables deep
2904 				 * directory support when security checks are
2905 				 * enabled. Otherwise, very long pathnames that
2906 				 * trigger an error here could evade the
2907 				 * sandbox.
2908 				 * TODO: We could do better, but it would
2909 				 * probably require merging the symlink checks
2910 				 * with the deep-directory editing.
2911 				 */
2912 				fsobj_error(a_eno, a_estr, errno,
2913 				    "Could not stat ", path);
2914 				res = ARCHIVE_FAILED;
2915 				break;
2916 			}
2917 		} else if (S_ISDIR(st.st_mode)) {
2918 			if (!last) {
2919 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2920 				fd = la_opendirat(chdir_fd, head);
2921 				if (fd < 0)
2922 					r = -1;
2923 				else {
2924 					r = 0;
2925 					close(chdir_fd);
2926 					chdir_fd = fd;
2927 				}
2928 #else
2929 				r = chdir(head);
2930 #endif
2931 				if (r != 0) {
2932 					tail[0] = c;
2933 					fsobj_error(a_eno, a_estr, errno,
2934 					    "Could not chdir ", path);
2935 					res = (ARCHIVE_FATAL);
2936 					break;
2937 				}
2938 				/* Our view is now from inside this dir: */
2939 				head = tail + 1;
2940 			}
2941 		} else if (S_ISLNK(st.st_mode)) {
2942 			if (last && checking_linkname) {
2943 #ifdef HAVE_LINKAT
2944 				/*
2945 				 * Hardlinks to symlinks are safe to write
2946 				 * if linkat() is supported as it does not
2947 				 * follow symlinks.
2948 				 */
2949 				res = ARCHIVE_OK;
2950 #else
2951 				/*
2952 				 * We return ARCHIVE_FAILED here as we are
2953 				 * not able to safely write hardlinks
2954 				 * to symlinks.
2955 				 */
2956 				tail[0] = c;
2957 				fsobj_error(a_eno, a_estr, errno,
2958 				    "Cannot write hardlink to symlink ",
2959 				    path);
2960 				res = ARCHIVE_FAILED;
2961 #endif
2962 				break;
2963 			} else
2964 			if (last) {
2965 				/*
2966 				 * Last element is symlink; remove it
2967 				 * so we can overwrite it with the
2968 				 * item being extracted.
2969 				 */
2970 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2971 				r = unlinkat(chdir_fd, head, 0);
2972 #else
2973 				r = unlink(head);
2974 #endif
2975 				if (r != 0) {
2976 					tail[0] = c;
2977 					fsobj_error(a_eno, a_estr, errno,
2978 					    "Could not remove symlink ",
2979 					    path);
2980 					res = ARCHIVE_FAILED;
2981 					break;
2982 				}
2983 				/*
2984 				 * Even if we did remove it, a warning
2985 				 * is in order.  The warning is silly,
2986 				 * though, if we're just replacing one
2987 				 * symlink with another symlink.
2988 				 */
2989 				tail[0] = c;
2990 				/*
2991 				 * FIXME:  not sure how important this is to
2992 				 * restore
2993 				 */
2994 				/*
2995 				if (!S_ISLNK(path)) {
2996 					fsobj_error(a_eno, a_estr, 0,
2997 					    "Removing symlink ", path);
2998 				}
2999 				*/
3000 				/* Symlink gone.  No more problem! */
3001 				res = ARCHIVE_OK;
3002 				break;
3003 			} else if (flags & ARCHIVE_EXTRACT_UNLINK) {
3004 				/* User asked us to remove problems. */
3005 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3006 				r = unlinkat(chdir_fd, head, 0);
3007 #else
3008 				r = unlink(head);
3009 #endif
3010 				if (r != 0) {
3011 					tail[0] = c;
3012 					fsobj_error(a_eno, a_estr, 0,
3013 					    "Cannot remove intervening "
3014 					    "symlink ", path);
3015 					res = ARCHIVE_FAILED;
3016 					break;
3017 				}
3018 				tail[0] = c;
3019 			} else if ((flags &
3020 			    ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
3021 				/*
3022 				 * We are not the last element and we want to
3023 				 * follow symlinks if they are a directory.
3024 				 *
3025 				 * This is needed to extract hardlinks over
3026 				 * symlinks.
3027 				 */
3028 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3029 				r = fstatat(chdir_fd, head, &st, 0);
3030 #else
3031 				r = la_stat(head, &st);
3032 #endif
3033 				if (r != 0) {
3034 					tail[0] = c;
3035 					if (errno == ENOENT) {
3036 						break;
3037 					} else {
3038 						fsobj_error(a_eno, a_estr,
3039 						    errno,
3040 						    "Could not stat ", path);
3041 						res = (ARCHIVE_FAILED);
3042 						break;
3043 					}
3044 				} else if (S_ISDIR(st.st_mode)) {
3045 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3046 					fd = la_opendirat(chdir_fd, head);
3047 					if (fd < 0)
3048 						r = -1;
3049 					else {
3050 						r = 0;
3051 						close(chdir_fd);
3052 						chdir_fd = fd;
3053 					}
3054 #else
3055 					r = chdir(head);
3056 #endif
3057 					if (r != 0) {
3058 						tail[0] = c;
3059 						fsobj_error(a_eno, a_estr,
3060 						    errno,
3061 						    "Could not chdir ", path);
3062 						res = (ARCHIVE_FATAL);
3063 						break;
3064 					}
3065 					/*
3066 					 * Our view is now from inside
3067 					 * this dir:
3068 					 */
3069 					head = tail + 1;
3070 				} else {
3071 					tail[0] = c;
3072 					fsobj_error(a_eno, a_estr, 0,
3073 					    "Cannot extract through "
3074 					    "symlink ", path);
3075 					res = ARCHIVE_FAILED;
3076 					break;
3077 				}
3078 			} else {
3079 				tail[0] = c;
3080 				fsobj_error(a_eno, a_estr, 0,
3081 				    "Cannot extract through symlink ", path);
3082 				res = ARCHIVE_FAILED;
3083 				break;
3084 			}
3085 		}
3086 		/* be sure to always maintain this */
3087 		tail[0] = c;
3088 		if (tail[0] != '\0')
3089 			tail++; /* Advance to the next segment. */
3090 	}
3091 	/* Catches loop exits via break */
3092 	tail[0] = c;
3093 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3094 	/* If we operate with openat(), fstatat() and unlinkat() there was
3095 	 * no chdir(), so just close the fd */
3096 	if (chdir_fd >= 0)
3097 		close(chdir_fd);
3098 #elif HAVE_FCHDIR
3099 	/* If we changed directory above, restore it here. */
3100 	if (chdir_fd >= 0) {
3101 		r = fchdir(chdir_fd);
3102 		if (r != 0) {
3103 			fsobj_error(a_eno, a_estr, errno,
3104 			    "chdir() failure", "");
3105 		}
3106 		close(chdir_fd);
3107 		chdir_fd = -1;
3108 		if (r != 0) {
3109 			res = (ARCHIVE_FATAL);
3110 		}
3111 	}
3112 #endif
3113 	/* TODO: reintroduce a safe cache here? */
3114 	return res;
3115 #endif
3116 }
3117 
3118 /*
3119  * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
3120  * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
3121  */
3122 static int
3123 check_symlinks(struct archive_write_disk *a)
3124 {
3125 	struct archive_string error_string;
3126 	int error_number;
3127 	int rc;
3128 	archive_string_init(&error_string);
3129 	rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
3130 	    a->flags, 0);
3131 	if (rc != ARCHIVE_OK) {
3132 		archive_set_error(&a->archive, error_number, "%s",
3133 		    error_string.s);
3134 	}
3135 	archive_string_free(&error_string);
3136 	a->pst = NULL;	/* to be safe */
3137 	return rc;
3138 }
3139 
3140 
3141 #if defined(__CYGWIN__)
3142 /*
3143  * 1. Convert a path separator from '\' to '/' .
3144  *    We shouldn't check multibyte character directly because some
3145  *    character-set have been using the '\' character for a part of
3146  *    its multibyte character code.
3147  * 2. Replace unusable characters in Windows with underscore('_').
3148  * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
3149  */
3150 static void
3151 cleanup_pathname_win(char *path)
3152 {
3153 	wchar_t wc;
3154 	char *p;
3155 	size_t alen, l;
3156 	int mb, complete, utf8;
3157 
3158 	alen = 0;
3159 	mb = 0;
3160 	complete = 1;
3161 	utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
3162 	for (p = path; *p != '\0'; p++) {
3163 		++alen;
3164 		if (*p == '\\') {
3165 			/* If previous byte is smaller than 128,
3166 			 * this is not second byte of multibyte characters,
3167 			 * so we can replace '\' with '/'. */
3168 			if (utf8 || !mb)
3169 				*p = '/';
3170 			else
3171 				complete = 0;/* uncompleted. */
3172 		} else if (*(unsigned char *)p > 127)
3173 			mb = 1;
3174 		else
3175 			mb = 0;
3176 		/* Rewrite the path name if its next character is unusable. */
3177 		if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
3178 		    *p == '<' || *p == '>' || *p == '|')
3179 			*p = '_';
3180 	}
3181 	if (complete)
3182 		return;
3183 
3184 	/*
3185 	 * Convert path separator in wide-character.
3186 	 */
3187 	p = path;
3188 	while (*p != '\0' && alen) {
3189 		l = mbtowc(&wc, p, alen);
3190 		if (l == (size_t)-1) {
3191 			while (*p != '\0') {
3192 				if (*p == '\\')
3193 					*p = '/';
3194 				++p;
3195 			}
3196 			break;
3197 		}
3198 		if (l == 1 && wc == L'\\')
3199 			*p = '/';
3200 		p += l;
3201 		alen -= l;
3202 	}
3203 }
3204 #endif
3205 
3206 /*
3207  * Canonicalize the pathname.  In particular, this strips duplicate
3208  * '/' characters, '.' elements, and trailing '/'.  It also raises an
3209  * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
3210  * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
3211  * is set) if the path is absolute.
3212  */
3213 static int
3214 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
3215     int flags)
3216 {
3217 	char *dest, *src;
3218 	char separator = '\0';
3219 
3220 	dest = src = path;
3221 	if (*src == '\0') {
3222 		fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3223 		    "Invalid empty ", "pathname");
3224 		return (ARCHIVE_FAILED);
3225 	}
3226 
3227 #if defined(__CYGWIN__)
3228 	cleanup_pathname_win(path);
3229 #endif
3230 	/* Skip leading '/'. */
3231 	if (*src == '/') {
3232 		if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
3233 			fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3234 			    "Path is ", "absolute");
3235 			return (ARCHIVE_FAILED);
3236 		}
3237 
3238 		separator = *src++;
3239 	}
3240 
3241 	/* Scan the pathname one element at a time. */
3242 	for (;;) {
3243 		/* src points to first char after '/' */
3244 		if (src[0] == '\0') {
3245 			break;
3246 		} else if (src[0] == '/') {
3247 			/* Found '//', ignore second one. */
3248 			src++;
3249 			continue;
3250 		} else if (src[0] == '.') {
3251 			if (src[1] == '\0') {
3252 				/* Ignore trailing '.' */
3253 				break;
3254 			} else if (src[1] == '/') {
3255 				/* Skip './'. */
3256 				src += 2;
3257 				continue;
3258 			} else if (src[1] == '.') {
3259 				if (src[2] == '/' || src[2] == '\0') {
3260 					/* Conditionally warn about '..' */
3261 					if (flags
3262 					    & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3263 						fsobj_error(a_eno, a_estr,
3264 						    ARCHIVE_ERRNO_MISC,
3265 						    "Path contains ", "'..'");
3266 						return (ARCHIVE_FAILED);
3267 					}
3268 				}
3269 				/*
3270 				 * Note: Under no circumstances do we
3271 				 * remove '..' elements.  In
3272 				 * particular, restoring
3273 				 * '/foo/../bar/' should create the
3274 				 * 'foo' dir as a side-effect.
3275 				 */
3276 			}
3277 		}
3278 
3279 		/* Copy current element, including leading '/'. */
3280 		if (separator)
3281 			*dest++ = '/';
3282 		while (*src != '\0' && *src != '/') {
3283 			*dest++ = *src++;
3284 		}
3285 
3286 		if (*src == '\0')
3287 			break;
3288 
3289 		/* Skip '/' separator. */
3290 		separator = *src++;
3291 	}
3292 	/*
3293 	 * We've just copied zero or more path elements, not including the
3294 	 * final '/'.
3295 	 */
3296 	if (dest == path) {
3297 		/*
3298 		 * Nothing got copied.  The path must have been something
3299 		 * like '.' or '/' or './' or '/././././/./'.
3300 		 */
3301 		if (separator)
3302 			*dest++ = '/';
3303 		else
3304 			*dest++ = '.';
3305 	}
3306 	/* Terminate the result. */
3307 	*dest = '\0';
3308 	return (ARCHIVE_OK);
3309 }
3310 
3311 static int
3312 cleanup_pathname(struct archive_write_disk *a)
3313 {
3314 	struct archive_string error_string;
3315 	int error_number;
3316 	int rc;
3317 	archive_string_init(&error_string);
3318 	rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3319 	    a->flags);
3320 	if (rc != ARCHIVE_OK) {
3321 		archive_set_error(&a->archive, error_number, "%s",
3322 		    error_string.s);
3323 	}
3324 	archive_string_free(&error_string);
3325 	return rc;
3326 }
3327 
3328 /*
3329  * Create the parent directory of the specified path, assuming path
3330  * is already in mutable storage.
3331  */
3332 static int
3333 create_parent_dir(struct archive_write_disk *a, char *path)
3334 {
3335 	char *slash;
3336 	int r;
3337 
3338 	/* Remove tail element to obtain parent name. */
3339 	slash = strrchr(path, '/');
3340 	if (slash == NULL)
3341 		return (ARCHIVE_OK);
3342 	*slash = '\0';
3343 	r = create_dir(a, path);
3344 	*slash = '/';
3345 	return (r);
3346 }
3347 
3348 /*
3349  * Create the specified dir, recursing to create parents as necessary.
3350  *
3351  * Returns ARCHIVE_OK if the path exists when we're done here.
3352  * Otherwise, returns ARCHIVE_FAILED.
3353  * Assumes path is in mutable storage; path is unchanged on exit.
3354  */
3355 static int
3356 create_dir(struct archive_write_disk *a, char *path)
3357 {
3358 	struct stat st;
3359 	struct fixup_entry *le;
3360 	char *slash, *base;
3361 	mode_t mode_final, mode;
3362 	int r;
3363 
3364 	/* Check for special names and just skip them. */
3365 	slash = strrchr(path, '/');
3366 	if (slash == NULL)
3367 		base = path;
3368 	else
3369 		base = slash + 1;
3370 
3371 	if (base[0] == '\0' ||
3372 	    (base[0] == '.' && base[1] == '\0') ||
3373 	    (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
3374 		/* Don't bother trying to create null path, '.', or '..'. */
3375 		if (slash != NULL) {
3376 			*slash = '\0';
3377 			r = create_dir(a, path);
3378 			*slash = '/';
3379 			return (r);
3380 		}
3381 		return (ARCHIVE_OK);
3382 	}
3383 
3384 	/*
3385 	 * Yes, this should be stat() and not lstat().  Using lstat()
3386 	 * here loses the ability to extract through symlinks.  Also note
3387 	 * that this should not use the a->st cache.
3388 	 */
3389 	if (la_stat(path, &st) == 0) {
3390 		if (S_ISDIR(st.st_mode))
3391 			return (ARCHIVE_OK);
3392 		if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
3393 			archive_set_error(&a->archive, EEXIST,
3394 			    "Can't create directory '%s'", path);
3395 			return (ARCHIVE_FAILED);
3396 		}
3397 		if (unlink(path) != 0) {
3398 			archive_set_error(&a->archive, errno,
3399 			    "Can't create directory '%s': "
3400 			    "Conflicting file cannot be removed",
3401 			    path);
3402 			return (ARCHIVE_FAILED);
3403 		}
3404 	} else if (errno != ENOENT && errno != ENOTDIR) {
3405 		/* Stat failed? */
3406 		archive_set_error(&a->archive, errno,
3407 		    "Can't test directory '%s'", path);
3408 		return (ARCHIVE_FAILED);
3409 	} else if (slash != NULL) {
3410 		*slash = '\0';
3411 		r = create_dir(a, path);
3412 		*slash = '/';
3413 		if (r != ARCHIVE_OK)
3414 			return (r);
3415 	}
3416 
3417 	/*
3418 	 * Mode we want for the final restored directory.  Per POSIX,
3419 	 * implicitly-created dirs must be created obeying the umask.
3420 	 * There's no mention whether this is different for privileged
3421 	 * restores (which the rest of this code handles by pretending
3422 	 * umask=0).  I've chosen here to always obey the user's umask for
3423 	 * implicit dirs, even if _EXTRACT_PERM was specified.
3424 	 */
3425 	mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3426 	/* Mode we want on disk during the restore process. */
3427 	mode = mode_final;
3428 	mode |= MINIMUM_DIR_MODE;
3429 	mode &= MAXIMUM_DIR_MODE;
3430 	if (mkdir(path, mode) == 0) {
3431 		if (mode != mode_final) {
3432 			le = new_fixup(a, path);
3433 			if (le == NULL)
3434 				return (ARCHIVE_FATAL);
3435 			le->fixup |=TODO_MODE_BASE;
3436 			le->mode = mode_final;
3437 		}
3438 		return (ARCHIVE_OK);
3439 	}
3440 
3441 	/*
3442 	 * Without the following check, a/b/../b/c/d fails at the
3443 	 * second visit to 'b', so 'd' can't be created.  Note that we
3444 	 * don't add it to the fixup list here, as it's already been
3445 	 * added.
3446 	 */
3447 	if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3448 		return (ARCHIVE_OK);
3449 
3450 	archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3451 	    path);
3452 	return (ARCHIVE_FAILED);
3453 }
3454 
3455 /*
3456  * Note: Although we can skip setting the user id if the desired user
3457  * id matches the current user, we cannot skip setting the group, as
3458  * many systems set the gid based on the containing directory.  So
3459  * we have to perform a chown syscall if we want to set the SGID
3460  * bit.  (The alternative is to stat() and then possibly chown(); it's
3461  * more efficient to skip the stat() and just always chown().)  Note
3462  * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3463  * allows set_mode to skip the stat() check for the GID.
3464  */
3465 static int
3466 set_ownership(struct archive_write_disk *a)
3467 {
3468 #if !defined(__CYGWIN__) && !defined(__linux__)
3469 /*
3470  * On Linux, a process may have the CAP_CHOWN capability.
3471  * On Windows there is no 'root' user with uid 0.
3472  * Elsewhere we can skip calling chown if we are not root and the desired
3473  * user id does not match the current user.
3474  */
3475 	if (a->user_uid != 0 && a->user_uid != a->uid) {
3476 		archive_set_error(&a->archive, errno,
3477 		    "Can't set UID=%jd", (intmax_t)a->uid);
3478 		return (ARCHIVE_WARN);
3479 	}
3480 #endif
3481 
3482 #ifdef HAVE_FCHOWN
3483 	/* If we have an fd, we can avoid a race. */
3484 	if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3485 		/* We've set owner and know uid/gid are correct. */
3486 		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3487 		return (ARCHIVE_OK);
3488 	}
3489 #endif
3490 
3491 	/* We prefer lchown() but will use chown() if that's all we have. */
3492 	/* Of course, if we have neither, this will always fail. */
3493 #ifdef HAVE_LCHOWN
3494 	if (lchown(a->name, a->uid, a->gid) == 0) {
3495 		/* We've set owner and know uid/gid are correct. */
3496 		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3497 		return (ARCHIVE_OK);
3498 	}
3499 #elif HAVE_CHOWN
3500 	if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3501 		/* We've set owner and know uid/gid are correct. */
3502 		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3503 		return (ARCHIVE_OK);
3504 	}
3505 #endif
3506 
3507 	archive_set_error(&a->archive, errno,
3508 	    "Can't set user=%jd/group=%jd for %s",
3509 	    (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3510 	return (ARCHIVE_WARN);
3511 }
3512 
3513 /*
3514  * Note: Returns 0 on success, non-zero on failure.
3515  */
3516 static int
3517 set_time(int fd, int mode, const char *name,
3518     time_t atime, long atime_nsec,
3519     time_t mtime, long mtime_nsec)
3520 {
3521 	/* Select the best implementation for this platform. */
3522 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3523 	/*
3524 	 * utimensat() and futimens() are defined in
3525 	 * POSIX.1-2008. They support ns resolution and setting times
3526 	 * on fds and symlinks.
3527 	 */
3528 	struct timespec ts[2];
3529 	(void)mode; /* UNUSED */
3530 	ts[0].tv_sec = atime;
3531 	ts[0].tv_nsec = atime_nsec;
3532 	ts[1].tv_sec = mtime;
3533 	ts[1].tv_nsec = mtime_nsec;
3534 	if (fd >= 0)
3535 		return futimens(fd, ts);
3536 	return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3537 
3538 #elif HAVE_UTIMES
3539 	/*
3540 	 * The utimes()-family functions support µs-resolution and
3541 	 * setting times fds and symlinks.  utimes() is documented as
3542 	 * LEGACY by POSIX, futimes() and lutimes() are not described
3543 	 * in POSIX.
3544 	 */
3545 	struct timeval times[2];
3546 
3547 	times[0].tv_sec = atime;
3548 	times[0].tv_usec = atime_nsec / 1000;
3549 	times[1].tv_sec = mtime;
3550 	times[1].tv_usec = mtime_nsec / 1000;
3551 
3552 #ifdef HAVE_FUTIMES
3553 	if (fd >= 0)
3554 		return (futimes(fd, times));
3555 #else
3556 	(void)fd; /* UNUSED */
3557 #endif
3558 #ifdef HAVE_LUTIMES
3559 	(void)mode; /* UNUSED */
3560 	return (lutimes(name, times));
3561 #else
3562 	if (S_ISLNK(mode))
3563 		return (0);
3564 	return (utimes(name, times));
3565 #endif
3566 
3567 #elif defined(HAVE_UTIME)
3568 	/*
3569 	 * utime() is POSIX-standard but only supports 1s resolution and
3570 	 * does not support fds or symlinks.
3571 	 */
3572 	struct utimbuf times;
3573 	(void)fd; /* UNUSED */
3574 	(void)name; /* UNUSED */
3575 	(void)atime_nsec; /* UNUSED */
3576 	(void)mtime_nsec; /* UNUSED */
3577 	times.actime = atime;
3578 	times.modtime = mtime;
3579 	if (S_ISLNK(mode))
3580 		return (ARCHIVE_OK);
3581 	return (utime(name, &times));
3582 
3583 #else
3584 	/*
3585 	 * We don't know how to set the time on this platform.
3586 	 */
3587 	(void)fd; /* UNUSED */
3588 	(void)mode; /* UNUSED */
3589 	(void)name; /* UNUSED */
3590 	(void)atime; /* UNUSED */
3591 	(void)atime_nsec; /* UNUSED */
3592 	(void)mtime; /* UNUSED */
3593 	(void)mtime_nsec; /* UNUSED */
3594 	return (ARCHIVE_WARN);
3595 #endif
3596 }
3597 
3598 #ifdef F_SETTIMES
3599 static int
3600 set_time_tru64(int fd, int mode, const char *name,
3601     time_t atime, long atime_nsec,
3602     time_t mtime, long mtime_nsec,
3603     time_t ctime, long ctime_nsec)
3604 {
3605 	struct attr_timbuf tstamp;
3606 	tstamp.atime.tv_sec = atime;
3607 	tstamp.mtime.tv_sec = mtime;
3608 	tstamp.ctime.tv_sec = ctime;
3609 #if defined (__hpux) && defined (__ia64)
3610 	tstamp.atime.tv_nsec = atime_nsec;
3611 	tstamp.mtime.tv_nsec = mtime_nsec;
3612 	tstamp.ctime.tv_nsec = ctime_nsec;
3613 #else
3614 	tstamp.atime.tv_usec = atime_nsec / 1000;
3615 	tstamp.mtime.tv_usec = mtime_nsec / 1000;
3616 	tstamp.ctime.tv_usec = ctime_nsec / 1000;
3617 #endif
3618 	return (fcntl(fd,F_SETTIMES,&tstamp));
3619 }
3620 #endif /* F_SETTIMES */
3621 
3622 static int
3623 set_times(struct archive_write_disk *a,
3624     int fd, int mode, const char *name,
3625     time_t atime, long atime_nanos,
3626     time_t birthtime, long birthtime_nanos,
3627     time_t mtime, long mtime_nanos,
3628     time_t cctime, long ctime_nanos)
3629 {
3630 	/* Note: set_time doesn't use libarchive return conventions!
3631 	 * It uses syscall conventions.  So 0 here instead of ARCHIVE_OK. */
3632 	int r1 = 0, r2 = 0;
3633 
3634 #ifdef F_SETTIMES
3635 	 /*
3636 	 * on Tru64 try own fcntl first which can restore even the
3637 	 * ctime, fall back to default code path below if it fails
3638 	 * or if we are not running as root
3639 	 */
3640 	if (a->user_uid == 0 &&
3641 	    set_time_tru64(fd, mode, name,
3642 			   atime, atime_nanos, mtime,
3643 			   mtime_nanos, cctime, ctime_nanos) == 0) {
3644 		return (ARCHIVE_OK);
3645 	}
3646 #else /* Tru64 */
3647 	(void)cctime; /* UNUSED */
3648 	(void)ctime_nanos; /* UNUSED */
3649 #endif /* Tru64 */
3650 
3651 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3652 	/*
3653 	 * If you have struct stat.st_birthtime, we assume BSD
3654 	 * birthtime semantics, in which {f,l,}utimes() updates
3655 	 * birthtime to earliest mtime.  So we set the time twice,
3656 	 * first using the birthtime, then using the mtime.  If
3657 	 * birthtime == mtime, this isn't necessary, so we skip it.
3658 	 * If birthtime > mtime, then this won't work, so we skip it.
3659 	 */
3660 	if (birthtime < mtime
3661 	    || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3662 		r1 = set_time(fd, mode, name,
3663 			      atime, atime_nanos,
3664 			      birthtime, birthtime_nanos);
3665 #else
3666 	(void)birthtime; /* UNUSED */
3667 	(void)birthtime_nanos; /* UNUSED */
3668 #endif
3669 	r2 = set_time(fd, mode, name,
3670 		      atime, atime_nanos,
3671 		      mtime, mtime_nanos);
3672 	if (r1 != 0 || r2 != 0) {
3673 		archive_set_error(&a->archive, errno,
3674 				  "Can't restore time");
3675 		return (ARCHIVE_WARN);
3676 	}
3677 	return (ARCHIVE_OK);
3678 }
3679 
3680 static int
3681 set_times_from_entry(struct archive_write_disk *a)
3682 {
3683 	time_t atime, birthtime, mtime, cctime;
3684 	long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3685 
3686 	/* Suitable defaults. */
3687 	atime = birthtime = mtime = cctime = a->start_time;
3688 	atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3689 
3690 	/* If no time was provided, we're done. */
3691 	if (!archive_entry_atime_is_set(a->entry)
3692 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
3693 	    && !archive_entry_birthtime_is_set(a->entry)
3694 #endif
3695 	    && !archive_entry_mtime_is_set(a->entry))
3696 		return (ARCHIVE_OK);
3697 
3698 	if (archive_entry_atime_is_set(a->entry)) {
3699 		atime = archive_entry_atime(a->entry);
3700 		atime_nsec = archive_entry_atime_nsec(a->entry);
3701 	}
3702 	if (archive_entry_birthtime_is_set(a->entry)) {
3703 		birthtime = archive_entry_birthtime(a->entry);
3704 		birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3705 	}
3706 	if (archive_entry_mtime_is_set(a->entry)) {
3707 		mtime = archive_entry_mtime(a->entry);
3708 		mtime_nsec = archive_entry_mtime_nsec(a->entry);
3709 	}
3710 	if (archive_entry_ctime_is_set(a->entry)) {
3711 		cctime = archive_entry_ctime(a->entry);
3712 		ctime_nsec = archive_entry_ctime_nsec(a->entry);
3713 	}
3714 
3715 	return set_times(a, a->fd, a->mode, a->name,
3716 			 atime, atime_nsec,
3717 			 birthtime, birthtime_nsec,
3718 			 mtime, mtime_nsec,
3719 			 cctime, ctime_nsec);
3720 }
3721 
3722 static int
3723 set_mode(struct archive_write_disk *a, int mode)
3724 {
3725 	int r = ARCHIVE_OK;
3726 	int r2;
3727 	mode &= 07777; /* Strip off file type bits. */
3728 
3729 	if (a->todo & TODO_SGID_CHECK) {
3730 		/*
3731 		 * If we don't know the GID is right, we must stat()
3732 		 * to verify it.  We can't just check the GID of this
3733 		 * process, since systems sometimes set GID from
3734 		 * the enclosing dir or based on ACLs.
3735 		 */
3736 		if ((r = lazy_stat(a)) != ARCHIVE_OK)
3737 			return (r);
3738 		if (a->pst->st_gid != a->gid) {
3739 			mode &= ~ S_ISGID;
3740 			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3741 				/*
3742 				 * This is only an error if you
3743 				 * requested owner restore.  If you
3744 				 * didn't, we'll try to restore
3745 				 * sgid/suid, but won't consider it a
3746 				 * problem if we can't.
3747 				 */
3748 				archive_set_error(&a->archive, -1,
3749 				    "Can't restore SGID bit");
3750 				r = ARCHIVE_WARN;
3751 			}
3752 		}
3753 		/* While we're here, double-check the UID. */
3754 		if (a->pst->st_uid != a->uid
3755 		    && (a->todo & TODO_SUID)) {
3756 			mode &= ~ S_ISUID;
3757 			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3758 				archive_set_error(&a->archive, -1,
3759 				    "Can't restore SUID bit");
3760 				r = ARCHIVE_WARN;
3761 			}
3762 		}
3763 		a->todo &= ~TODO_SGID_CHECK;
3764 		a->todo &= ~TODO_SUID_CHECK;
3765 	} else if (a->todo & TODO_SUID_CHECK) {
3766 		/*
3767 		 * If we don't know the UID is right, we can just check
3768 		 * the user, since all systems set the file UID from
3769 		 * the process UID.
3770 		 */
3771 		if (a->user_uid != a->uid) {
3772 			mode &= ~ S_ISUID;
3773 			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3774 				archive_set_error(&a->archive, -1,
3775 				    "Can't make file SUID");
3776 				r = ARCHIVE_WARN;
3777 			}
3778 		}
3779 		a->todo &= ~TODO_SUID_CHECK;
3780 	}
3781 
3782 	if (S_ISLNK(a->mode)) {
3783 #ifdef HAVE_LCHMOD
3784 		/*
3785 		 * If this is a symlink, use lchmod().  If the
3786 		 * platform doesn't support lchmod(), just skip it.  A
3787 		 * platform that doesn't provide a way to set
3788 		 * permissions on symlinks probably ignores
3789 		 * permissions on symlinks, so a failure here has no
3790 		 * impact.
3791 		 */
3792 		if (lchmod(a->name, mode) != 0) {
3793 			switch (errno) {
3794 			case ENOTSUP:
3795 			case ENOSYS:
3796 #if ENOTSUP != EOPNOTSUPP
3797 			case EOPNOTSUPP:
3798 #endif
3799 				/*
3800 				 * if lchmod is defined but the platform
3801 				 * doesn't support it, silently ignore
3802 				 * error
3803 				 */
3804 				break;
3805 			default:
3806 				archive_set_error(&a->archive, errno,
3807 				    "Can't set permissions to 0%o", (int)mode);
3808 				r = ARCHIVE_WARN;
3809 			}
3810 		}
3811 #endif
3812 	} else if (!S_ISDIR(a->mode)) {
3813 		/*
3814 		 * If it's not a symlink and not a dir, then use
3815 		 * fchmod() or chmod(), depending on whether we have
3816 		 * an fd.  Dirs get their perms set during the
3817 		 * post-extract fixup, which is handled elsewhere.
3818 		 */
3819 #ifdef HAVE_FCHMOD
3820 		if (a->fd >= 0)
3821 			r2 = fchmod(a->fd, mode);
3822 		else
3823 #endif
3824 		/* If this platform lacks fchmod(), then
3825 		 * we'll just use chmod(). */
3826 		r2 = chmod(a->name, mode);
3827 
3828 		if (r2 != 0) {
3829 			archive_set_error(&a->archive, errno,
3830 			    "Can't set permissions to 0%o", (int)mode);
3831 			r = ARCHIVE_WARN;
3832 		}
3833 	}
3834 	return (r);
3835 }
3836 
3837 static int
3838 set_fflags(struct archive_write_disk *a)
3839 {
3840 	struct fixup_entry *le;
3841 	unsigned long	set, clear;
3842 	int		r;
3843 	mode_t		mode = archive_entry_mode(a->entry);
3844 	/*
3845 	 * Make 'critical_flags' hold all file flags that can't be
3846 	 * immediately restored.  For example, on BSD systems,
3847 	 * SF_IMMUTABLE prevents hardlinks from being created, so
3848 	 * should not be set until after any hardlinks are created.  To
3849 	 * preserve some semblance of portability, this uses #ifdef
3850 	 * extensively.  Ugly, but it works.
3851 	 *
3852 	 * Yes, Virginia, this does create a security race.  It's mitigated
3853 	 * somewhat by the practice of creating dirs 0700 until the extract
3854 	 * is done, but it would be nice if we could do more than that.
3855 	 * People restoring critical file systems should be wary of
3856 	 * other programs that might try to muck with files as they're
3857 	 * being restored.
3858 	 */
3859 	const int	critical_flags = 0
3860 #ifdef SF_IMMUTABLE
3861 	    | SF_IMMUTABLE
3862 #endif
3863 #ifdef UF_IMMUTABLE
3864 	    | UF_IMMUTABLE
3865 #endif
3866 #ifdef SF_APPEND
3867 	    | SF_APPEND
3868 #endif
3869 #ifdef UF_APPEND
3870 	    | UF_APPEND
3871 #endif
3872 #if defined(FS_APPEND_FL)
3873 	    | FS_APPEND_FL
3874 #elif defined(EXT2_APPEND_FL)
3875 	    | EXT2_APPEND_FL
3876 #endif
3877 #if defined(FS_IMMUTABLE_FL)
3878 	    | FS_IMMUTABLE_FL
3879 #elif defined(EXT2_IMMUTABLE_FL)
3880 	    | EXT2_IMMUTABLE_FL
3881 #endif
3882 #ifdef FS_JOURNAL_DATA_FL
3883 	    | FS_JOURNAL_DATA_FL
3884 #endif
3885 	;
3886 
3887 	if (a->todo & TODO_FFLAGS) {
3888 		archive_entry_fflags(a->entry, &set, &clear);
3889 
3890 		/*
3891 		 * The first test encourages the compiler to eliminate
3892 		 * all of this if it's not necessary.
3893 		 */
3894 		if ((critical_flags != 0)  &&  (set & critical_flags)) {
3895 			le = current_fixup(a, a->name);
3896 			if (le == NULL)
3897 				return (ARCHIVE_FATAL);
3898 			le->filetype = archive_entry_filetype(a->entry);
3899 			le->fixup |= TODO_FFLAGS;
3900 			le->fflags_set = set;
3901 			/* Store the mode if it's not already there. */
3902 			if ((le->fixup & TODO_MODE) == 0)
3903 				le->mode = mode;
3904 		} else {
3905 			r = set_fflags_platform(a, a->fd,
3906 			    a->name, mode, set, clear);
3907 			if (r != ARCHIVE_OK)
3908 				return (r);
3909 		}
3910 	}
3911 	return (ARCHIVE_OK);
3912 }
3913 
3914 static int
3915 clear_nochange_fflags(struct archive_write_disk *a)
3916 {
3917 	mode_t		mode = archive_entry_mode(a->entry);
3918 	const int nochange_flags = 0
3919 #ifdef SF_IMMUTABLE
3920 	    | SF_IMMUTABLE
3921 #endif
3922 #ifdef UF_IMMUTABLE
3923 	    | UF_IMMUTABLE
3924 #endif
3925 #ifdef SF_APPEND
3926 	    | SF_APPEND
3927 #endif
3928 #ifdef UF_APPEND
3929 	    | UF_APPEND
3930 #endif
3931 #ifdef EXT2_APPEND_FL
3932 	    | EXT2_APPEND_FL
3933 #endif
3934 #ifdef EXT2_IMMUTABLE_FL
3935 	    | EXT2_IMMUTABLE_FL
3936 #endif
3937 	;
3938 
3939 	return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3940 	    nochange_flags));
3941 }
3942 
3943 
3944 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3945 /*
3946  * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3947  */
3948 static int
3949 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3950     mode_t mode, unsigned long set, unsigned long clear)
3951 {
3952 	int r;
3953 	const int sf_mask = 0
3954 #ifdef SF_APPEND
3955 	    | SF_APPEND
3956 #endif
3957 #ifdef SF_ARCHIVED
3958 	    | SF_ARCHIVED
3959 #endif
3960 #ifdef SF_IMMUTABLE
3961 	    | SF_IMMUTABLE
3962 #endif
3963 #ifdef SF_NOUNLINK
3964 	    | SF_NOUNLINK
3965 #endif
3966 	;
3967 	(void)mode; /* UNUSED */
3968 
3969 	if (set == 0  && clear == 0)
3970 		return (ARCHIVE_OK);
3971 
3972 	/*
3973 	 * XXX Is the stat here really necessary?  Or can I just use
3974 	 * the 'set' flags directly?  In particular, I'm not sure
3975 	 * about the correct approach if we're overwriting an existing
3976 	 * file that already has flags on it. XXX
3977 	 */
3978 	if ((r = lazy_stat(a)) != ARCHIVE_OK)
3979 		return (r);
3980 
3981 	a->st.st_flags &= ~clear;
3982 	a->st.st_flags |= set;
3983 
3984 	/* Only super-user may change SF_* flags */
3985 
3986 	if (a->user_uid != 0)
3987 		a->st.st_flags &= ~sf_mask;
3988 
3989 #ifdef HAVE_FCHFLAGS
3990 	/* If platform has fchflags() and we were given an fd, use it. */
3991 	if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
3992 		return (ARCHIVE_OK);
3993 #endif
3994 	/*
3995 	 * If we can't use the fd to set the flags, we'll use the
3996 	 * pathname to set flags.  We prefer lchflags() but will use
3997 	 * chflags() if we must.
3998 	 */
3999 #ifdef HAVE_LCHFLAGS
4000 	if (lchflags(name, a->st.st_flags) == 0)
4001 		return (ARCHIVE_OK);
4002 #elif defined(HAVE_CHFLAGS)
4003 	if (S_ISLNK(a->st.st_mode)) {
4004 		archive_set_error(&a->archive, errno,
4005 		    "Can't set file flags on symlink.");
4006 		return (ARCHIVE_WARN);
4007 	}
4008 	if (chflags(name, a->st.st_flags) == 0)
4009 		return (ARCHIVE_OK);
4010 #endif
4011 	archive_set_error(&a->archive, errno,
4012 	    "Failed to set file flags");
4013 	return (ARCHIVE_WARN);
4014 }
4015 
4016 #elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \
4017        defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
4018       (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \
4019        defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
4020 /*
4021  * Linux uses ioctl() to read and write file flags.
4022  */
4023 static int
4024 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4025     mode_t mode, unsigned long set, unsigned long clear)
4026 {
4027 	int		 ret;
4028 	int		 myfd = fd;
4029 	int newflags, oldflags;
4030 	/*
4031 	 * Linux has no define for the flags that are only settable by
4032 	 * the root user.  This code may seem a little complex, but
4033 	 * there seem to be some Linux systems that lack these
4034 	 * defines. (?)  The code below degrades reasonably gracefully
4035 	 * if sf_mask is incomplete.
4036 	 */
4037 	const int sf_mask = 0
4038 #if defined(FS_IMMUTABLE_FL)
4039 	    | FS_IMMUTABLE_FL
4040 #elif defined(EXT2_IMMUTABLE_FL)
4041 	    | EXT2_IMMUTABLE_FL
4042 #endif
4043 #if defined(FS_APPEND_FL)
4044 	    | FS_APPEND_FL
4045 #elif defined(EXT2_APPEND_FL)
4046 	    | EXT2_APPEND_FL
4047 #endif
4048 #if defined(FS_JOURNAL_DATA_FL)
4049 	    | FS_JOURNAL_DATA_FL
4050 #endif
4051 	;
4052 
4053 	if (set == 0 && clear == 0)
4054 		return (ARCHIVE_OK);
4055 	/* Only regular files and dirs can have flags. */
4056 	if (!S_ISREG(mode) && !S_ISDIR(mode))
4057 		return (ARCHIVE_OK);
4058 
4059 	/* If we weren't given an fd, open it ourselves. */
4060 	if (myfd < 0) {
4061 		myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY |
4062 		    O_CLOEXEC | O_NOFOLLOW);
4063 		__archive_ensure_cloexec_flag(myfd);
4064 	}
4065 	if (myfd < 0)
4066 		return (ARCHIVE_OK);
4067 
4068 	/*
4069 	 * XXX As above, this would be way simpler if we didn't have
4070 	 * to read the current flags from disk. XXX
4071 	 */
4072 	ret = ARCHIVE_OK;
4073 
4074 	/* Read the current file flags. */
4075 	if (ioctl(myfd,
4076 #ifdef FS_IOC_GETFLAGS
4077 	    FS_IOC_GETFLAGS,
4078 #else
4079 	    EXT2_IOC_GETFLAGS,
4080 #endif
4081 	    &oldflags) < 0)
4082 		goto fail;
4083 
4084 	/* Try setting the flags as given. */
4085 	newflags = (oldflags & ~clear) | set;
4086 	if (ioctl(myfd,
4087 #ifdef FS_IOC_SETFLAGS
4088 	    FS_IOC_SETFLAGS,
4089 #else
4090 	    EXT2_IOC_SETFLAGS,
4091 #endif
4092 	    &newflags) >= 0)
4093 		goto cleanup;
4094 	if (errno != EPERM)
4095 		goto fail;
4096 
4097 	/* If we couldn't set all the flags, try again with a subset. */
4098 	newflags &= ~sf_mask;
4099 	oldflags &= sf_mask;
4100 	newflags |= oldflags;
4101 	if (ioctl(myfd,
4102 #ifdef FS_IOC_SETFLAGS
4103 	    FS_IOC_SETFLAGS,
4104 #else
4105 	    EXT2_IOC_SETFLAGS,
4106 #endif
4107 	    &newflags) >= 0)
4108 		goto cleanup;
4109 
4110 	/* We couldn't set the flags, so report the failure. */
4111 fail:
4112 	archive_set_error(&a->archive, errno,
4113 	    "Failed to set file flags");
4114 	ret = ARCHIVE_WARN;
4115 cleanup:
4116 	if (fd < 0)
4117 		close(myfd);
4118 	return (ret);
4119 }
4120 
4121 #else
4122 
4123 /*
4124  * Of course, some systems have neither BSD chflags() nor Linux' flags
4125  * support through ioctl().
4126  */
4127 static int
4128 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4129     mode_t mode, unsigned long set, unsigned long clear)
4130 {
4131 	(void)a; /* UNUSED */
4132 	(void)fd; /* UNUSED */
4133 	(void)name; /* UNUSED */
4134 	(void)mode; /* UNUSED */
4135 	(void)set; /* UNUSED */
4136 	(void)clear; /* UNUSED */
4137 	return (ARCHIVE_OK);
4138 }
4139 
4140 #endif /* __linux */
4141 
4142 #ifndef HAVE_COPYFILE_H
4143 /* Default is to simply drop Mac extended metadata. */
4144 static int
4145 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4146 		 const void *metadata, size_t metadata_size)
4147 {
4148 	(void)a; /* UNUSED */
4149 	(void)pathname; /* UNUSED */
4150 	(void)metadata; /* UNUSED */
4151 	(void)metadata_size; /* UNUSED */
4152 	return (ARCHIVE_OK);
4153 }
4154 
4155 static int
4156 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4157 {
4158 	(void)a; /* UNUSED */
4159 	(void)pathname; /* UNUSED */
4160 	return (ARCHIVE_OK);
4161 }
4162 #else
4163 
4164 /*
4165  * On Mac OS, we use copyfile() to unpack the metadata and
4166  * apply it to the target file.
4167  */
4168 
4169 #if defined(HAVE_SYS_XATTR_H)
4170 static int
4171 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
4172 {
4173 	ssize_t xattr_size;
4174 	char *xattr_names = NULL, *xattr_val = NULL;
4175 	int ret = ARCHIVE_OK, xattr_i;
4176 
4177 	xattr_size = flistxattr(tmpfd, NULL, 0, 0);
4178 	if (xattr_size == -1) {
4179 		archive_set_error(&a->archive, errno,
4180 		    "Failed to read metadata(xattr)");
4181 		ret = ARCHIVE_WARN;
4182 		goto exit_xattr;
4183 	}
4184 	xattr_names = malloc(xattr_size);
4185 	if (xattr_names == NULL) {
4186 		archive_set_error(&a->archive, ENOMEM,
4187 		    "Can't allocate memory for metadata(xattr)");
4188 		ret = ARCHIVE_FATAL;
4189 		goto exit_xattr;
4190 	}
4191 	xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
4192 	if (xattr_size == -1) {
4193 		archive_set_error(&a->archive, errno,
4194 		    "Failed to read metadata(xattr)");
4195 		ret = ARCHIVE_WARN;
4196 		goto exit_xattr;
4197 	}
4198 	for (xattr_i = 0; xattr_i < xattr_size;
4199 	    xattr_i += strlen(xattr_names + xattr_i) + 1) {
4200 		char *xattr_val_saved;
4201 		ssize_t s;
4202 		int f;
4203 
4204 		s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
4205 		if (s == -1) {
4206 			archive_set_error(&a->archive, errno,
4207 			    "Failed to get metadata(xattr)");
4208 			ret = ARCHIVE_WARN;
4209 			goto exit_xattr;
4210 		}
4211 		xattr_val_saved = xattr_val;
4212 		xattr_val = realloc(xattr_val, s);
4213 		if (xattr_val == NULL) {
4214 			archive_set_error(&a->archive, ENOMEM,
4215 			    "Failed to get metadata(xattr)");
4216 			ret = ARCHIVE_WARN;
4217 			free(xattr_val_saved);
4218 			goto exit_xattr;
4219 		}
4220 		s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4221 		if (s == -1) {
4222 			archive_set_error(&a->archive, errno,
4223 			    "Failed to get metadata(xattr)");
4224 			ret = ARCHIVE_WARN;
4225 			goto exit_xattr;
4226 		}
4227 		f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4228 		if (f == -1) {
4229 			archive_set_error(&a->archive, errno,
4230 			    "Failed to get metadata(xattr)");
4231 			ret = ARCHIVE_WARN;
4232 			goto exit_xattr;
4233 		}
4234 	}
4235 exit_xattr:
4236 	free(xattr_names);
4237 	free(xattr_val);
4238 	return (ret);
4239 }
4240 #endif
4241 
4242 static int
4243 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
4244 {
4245 #ifndef HAVE_SYS_ACL_H
4246 	return 0;
4247 #else
4248 	acl_t acl, dfacl = NULL;
4249 	int acl_r, ret = ARCHIVE_OK;
4250 
4251 	acl = acl_get_fd(tmpfd);
4252 	if (acl == NULL) {
4253 		if (errno == ENOENT)
4254 			/* There are not any ACLs. */
4255 			return (ret);
4256 		archive_set_error(&a->archive, errno,
4257 		    "Failed to get metadata(acl)");
4258 		ret = ARCHIVE_WARN;
4259 		goto exit_acl;
4260 	}
4261 	dfacl = acl_dup(acl);
4262 	acl_r = acl_set_fd(dffd, dfacl);
4263 	if (acl_r == -1) {
4264 		archive_set_error(&a->archive, errno,
4265 		    "Failed to get metadata(acl)");
4266 		ret = ARCHIVE_WARN;
4267 		goto exit_acl;
4268 	}
4269 exit_acl:
4270 	if (acl)
4271 		acl_free(acl);
4272 	if (dfacl)
4273 		acl_free(dfacl);
4274 	return (ret);
4275 #endif
4276 }
4277 
4278 static int
4279 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4280 {
4281 	struct archive_string tmpdatafork;
4282 	int tmpfd;
4283 
4284 	archive_string_init(&tmpdatafork);
4285 	archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
4286 	tmpfd = mkstemp(tmpdatafork.s);
4287 	if (tmpfd < 0) {
4288 		archive_set_error(&a->archive, errno,
4289 		    "Failed to mkstemp");
4290 		archive_string_free(&tmpdatafork);
4291 		return (-1);
4292 	}
4293 	if (copyfile(pathname, tmpdatafork.s, 0,
4294 	    COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4295 	    | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4296 		archive_set_error(&a->archive, errno,
4297 		    "Failed to restore metadata");
4298 		close(tmpfd);
4299 		tmpfd = -1;
4300 	}
4301 	unlink(tmpdatafork.s);
4302 	archive_string_free(&tmpdatafork);
4303 	return (tmpfd);
4304 }
4305 
4306 static int
4307 copy_metadata(struct archive_write_disk *a, const char *metadata,
4308     const char *datafork, int datafork_compressed)
4309 {
4310 	int ret = ARCHIVE_OK;
4311 
4312 	if (datafork_compressed) {
4313 		int dffd, tmpfd;
4314 
4315 		tmpfd = create_tempdatafork(a, metadata);
4316 		if (tmpfd == -1)
4317 			return (ARCHIVE_WARN);
4318 
4319 		/*
4320 		 * Do not open the data fork compressed by HFS+ compression
4321 		 * with at least a writing mode(O_RDWR or O_WRONLY). it
4322 		 * makes the data fork uncompressed.
4323 		 */
4324 		dffd = open(datafork, 0);
4325 		if (dffd == -1) {
4326 			archive_set_error(&a->archive, errno,
4327 			    "Failed to open the data fork for metadata");
4328 			close(tmpfd);
4329 			return (ARCHIVE_WARN);
4330 		}
4331 
4332 #if defined(HAVE_SYS_XATTR_H)
4333 		ret = copy_xattrs(a, tmpfd, dffd);
4334 		if (ret == ARCHIVE_OK)
4335 #endif
4336 			ret = copy_acls(a, tmpfd, dffd);
4337 		close(tmpfd);
4338 		close(dffd);
4339 	} else {
4340 		if (copyfile(metadata, datafork, 0,
4341 		    COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4342 		    | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4343 			archive_set_error(&a->archive, errno,
4344 			    "Failed to restore metadata");
4345 			ret = ARCHIVE_WARN;
4346 		}
4347 	}
4348 	return (ret);
4349 }
4350 
4351 static int
4352 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4353 		 const void *metadata, size_t metadata_size)
4354 {
4355 	struct archive_string tmp;
4356 	ssize_t written;
4357 	int fd;
4358 	int ret = ARCHIVE_OK;
4359 
4360 	/* This would be simpler if copyfile() could just accept the
4361 	 * metadata as a block of memory; then we could sidestep this
4362 	 * silly dance of writing the data to disk just so that
4363 	 * copyfile() can read it back in again. */
4364 	archive_string_init(&tmp);
4365 	archive_strcpy(&tmp, pathname);
4366 	archive_strcat(&tmp, ".XXXXXX");
4367 	fd = mkstemp(tmp.s);
4368 
4369 	if (fd < 0) {
4370 		archive_set_error(&a->archive, errno,
4371 				  "Failed to restore metadata");
4372 		archive_string_free(&tmp);
4373 		return (ARCHIVE_WARN);
4374 	}
4375 	written = write(fd, metadata, metadata_size);
4376 	close(fd);
4377 	if ((size_t)written != metadata_size) {
4378 		archive_set_error(&a->archive, errno,
4379 				  "Failed to restore metadata");
4380 		ret = ARCHIVE_WARN;
4381 	} else {
4382 		int compressed;
4383 
4384 #if defined(UF_COMPRESSED)
4385 		if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
4386 		    (ret = lazy_stat(a)) == ARCHIVE_OK)
4387 			compressed = a->st.st_flags & UF_COMPRESSED;
4388 		else
4389 #endif
4390 			compressed = 0;
4391 		ret = copy_metadata(a, tmp.s, pathname, compressed);
4392 	}
4393 	unlink(tmp.s);
4394 	archive_string_free(&tmp);
4395 	return (ret);
4396 }
4397 
4398 static int
4399 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4400 {
4401 	char buff[8];
4402 	struct stat st;
4403 	const char *p;
4404 	struct archive_string datafork;
4405 	int fd = -1, ret = ARCHIVE_OK;
4406 
4407 	archive_string_init(&datafork);
4408 	/* Check if the current file name is a type of the resource
4409 	 * fork file. */
4410 	p = strrchr(pathname, '/');
4411 	if (p == NULL)
4412 		p = pathname;
4413 	else
4414 		p++;
4415 	if (p[0] != '.' || p[1] != '_')
4416 		goto skip_appledouble;
4417 
4418 	/*
4419 	 * Check if the data fork file exists.
4420 	 *
4421 	 * TODO: Check if this write disk object has handled it.
4422 	 */
4423 	archive_strncpy(&datafork, pathname, p - pathname);
4424 	archive_strcat(&datafork, p + 2);
4425 	if (
4426 #ifdef HAVE_LSTAT
4427 		lstat(datafork.s, &st) == -1 ||
4428 #else
4429 		la_stat(datafork.s, &st) == -1 ||
4430 #endif
4431 	    (st.st_mode & AE_IFMT) != AE_IFREG)
4432 		goto skip_appledouble;
4433 
4434 	/*
4435 	 * Check if the file is in the AppleDouble form.
4436 	 */
4437 	fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4438 	__archive_ensure_cloexec_flag(fd);
4439 	if (fd == -1) {
4440 		archive_set_error(&a->archive, errno,
4441 		    "Failed to open a restoring file");
4442 		ret = ARCHIVE_WARN;
4443 		goto skip_appledouble;
4444 	}
4445 	if (read(fd, buff, 8) == -1) {
4446 		archive_set_error(&a->archive, errno,
4447 		    "Failed to read a restoring file");
4448 		close(fd);
4449 		ret = ARCHIVE_WARN;
4450 		goto skip_appledouble;
4451 	}
4452 	close(fd);
4453 	/* Check AppleDouble Magic Code. */
4454 	if (archive_be32dec(buff) != 0x00051607)
4455 		goto skip_appledouble;
4456 	/* Check AppleDouble Version. */
4457 	if (archive_be32dec(buff+4) != 0x00020000)
4458 		goto skip_appledouble;
4459 
4460 	ret = copy_metadata(a, pathname, datafork.s,
4461 #if defined(UF_COMPRESSED)
4462 	    st.st_flags & UF_COMPRESSED);
4463 #else
4464 	    0);
4465 #endif
4466 	if (ret == ARCHIVE_OK) {
4467 		unlink(pathname);
4468 		ret = ARCHIVE_EOF;
4469 	}
4470 skip_appledouble:
4471 	archive_string_free(&datafork);
4472 	return (ret);
4473 }
4474 #endif
4475 
4476 #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4477 /*
4478  * Restore extended attributes -  Linux, Darwin and AIX implementations:
4479  * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4480  */
4481 static int
4482 set_xattrs(struct archive_write_disk *a)
4483 {
4484 	struct archive_entry *entry = a->entry;
4485 	struct archive_string errlist;
4486 	int ret = ARCHIVE_OK;
4487 	int i = archive_entry_xattr_reset(entry);
4488 	short fail = 0;
4489 
4490 	archive_string_init(&errlist);
4491 
4492 	while (i--) {
4493 		const char *name;
4494 		const void *value;
4495 		size_t size;
4496 		int e;
4497 
4498 		archive_entry_xattr_next(entry, &name, &value, &size);
4499 
4500 		if (name == NULL)
4501 			continue;
4502 #if ARCHIVE_XATTR_LINUX
4503 		/* Linux: quietly skip POSIX.1e ACL extended attributes */
4504 		if (strncmp(name, "system.", 7) == 0 &&
4505 		   (strcmp(name + 7, "posix_acl_access") == 0 ||
4506 		    strcmp(name + 7, "posix_acl_default") == 0))
4507 			continue;
4508 		if (strncmp(name, "trusted.SGI_", 12) == 0 &&
4509 		   (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
4510 		    strcmp(name + 12, "ACL_FILE") == 0))
4511 			continue;
4512 
4513 		/* Linux: xfsroot namespace is obsolete and unsupported */
4514 		if (strncmp(name, "xfsroot.", 8) == 0) {
4515 			fail = 1;
4516 			archive_strcat(&errlist, name);
4517 			archive_strappend_char(&errlist, ' ');
4518 			continue;
4519 		}
4520 #endif
4521 
4522 		if (a->fd >= 0) {
4523 #if ARCHIVE_XATTR_LINUX
4524 			e = fsetxattr(a->fd, name, value, size, 0);
4525 #elif ARCHIVE_XATTR_DARWIN
4526 			e = fsetxattr(a->fd, name, value, size, 0, 0);
4527 #elif ARCHIVE_XATTR_AIX
4528 			e = fsetea(a->fd, name, value, size, 0);
4529 #endif
4530 		} else {
4531 #if ARCHIVE_XATTR_LINUX
4532 			e = lsetxattr(archive_entry_pathname(entry),
4533 			    name, value, size, 0);
4534 #elif ARCHIVE_XATTR_DARWIN
4535 			e = setxattr(archive_entry_pathname(entry),
4536 			    name, value, size, 0, XATTR_NOFOLLOW);
4537 #elif ARCHIVE_XATTR_AIX
4538 			e = lsetea(archive_entry_pathname(entry),
4539 			    name, value, size, 0);
4540 #endif
4541 		}
4542 		if (e == -1) {
4543 			ret = ARCHIVE_WARN;
4544 			archive_strcat(&errlist, name);
4545 			archive_strappend_char(&errlist, ' ');
4546 			if (errno != ENOTSUP && errno != ENOSYS)
4547 				fail = 1;
4548 		}
4549 	}
4550 
4551 	if (ret == ARCHIVE_WARN) {
4552 		if (fail && errlist.length > 0) {
4553 			errlist.length--;
4554 			errlist.s[errlist.length] = '\0';
4555 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4556 			    "Cannot restore extended attributes: %s",
4557 			    errlist.s);
4558 		} else
4559 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4560 			    "Cannot restore extended "
4561 			    "attributes on this file system.");
4562 	}
4563 
4564 	archive_string_free(&errlist);
4565 	return (ret);
4566 }
4567 #elif ARCHIVE_XATTR_FREEBSD
4568 /*
4569  * Restore extended attributes -  FreeBSD implementation
4570  */
4571 static int
4572 set_xattrs(struct archive_write_disk *a)
4573 {
4574 	struct archive_entry *entry = a->entry;
4575 	struct archive_string errlist;
4576 	int ret = ARCHIVE_OK;
4577 	int i = archive_entry_xattr_reset(entry);
4578 	short fail = 0;
4579 
4580 	archive_string_init(&errlist);
4581 
4582 	while (i--) {
4583 		const char *name;
4584 		const void *value;
4585 		size_t size;
4586 		archive_entry_xattr_next(entry, &name, &value, &size);
4587 		if (name != NULL) {
4588 			ssize_t e;
4589 			int namespace;
4590 
4591 			namespace = EXTATTR_NAMESPACE_USER;
4592 
4593 			if (strncmp(name, "user.", 5) == 0) {
4594 				/* "user." attributes go to user namespace */
4595 				name += 5;
4596 				namespace = EXTATTR_NAMESPACE_USER;
4597 			} else if (strncmp(name, "system.", 7) == 0) {
4598 				name += 7;
4599 				namespace = EXTATTR_NAMESPACE_SYSTEM;
4600 				if (!strcmp(name, "nfs4.acl") ||
4601 				    !strcmp(name, "posix1e.acl_access") ||
4602 				    !strcmp(name, "posix1e.acl_default"))
4603 					continue;
4604 			} else {
4605 				/* Other namespaces are unsupported */
4606 				archive_strcat(&errlist, name);
4607 				archive_strappend_char(&errlist, ' ');
4608 				fail = 1;
4609 				ret = ARCHIVE_WARN;
4610 				continue;
4611 			}
4612 
4613 			if (a->fd >= 0) {
4614 				/*
4615 				 * On FreeBSD, extattr_set_fd does not
4616 				 * return the same as
4617 				 * extattr_set_file. It returns zero
4618 				 * on success, non-zero on failure.
4619 				 *
4620 				 * We can detect the failure by
4621 				 * manually setting errno prior to the
4622 				 * call and checking after.
4623 				 *
4624 				 * If errno remains zero, fake the
4625 				 * return value by setting e to size.
4626 				 *
4627 				 * This is a hack for now until I
4628 				 * (Shawn Webb) get FreeBSD to fix the
4629 				 * issue, if that's even possible.
4630 				 */
4631 				errno = 0;
4632 				e = extattr_set_fd(a->fd, namespace, name,
4633 				    value, size);
4634 				if (e == 0 && errno == 0) {
4635 					e = size;
4636 				}
4637 			} else {
4638 				e = extattr_set_link(
4639 				    archive_entry_pathname(entry), namespace,
4640 				    name, value, size);
4641 			}
4642 			if (e != (ssize_t)size) {
4643 				archive_strcat(&errlist, name);
4644 				archive_strappend_char(&errlist, ' ');
4645 				ret = ARCHIVE_WARN;
4646 				if (errno != ENOTSUP && errno != ENOSYS)
4647 					fail = 1;
4648 			}
4649 		}
4650 	}
4651 
4652 	if (ret == ARCHIVE_WARN) {
4653 		if (fail && errlist.length > 0) {
4654 			errlist.length--;
4655 			errlist.s[errlist.length] = '\0';
4656 
4657 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4658 			    "Cannot restore extended attributes: %s",
4659 			    errlist.s);
4660 		} else
4661 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4662 			    "Cannot restore extended "
4663 			    "attributes on this file system.");
4664 	}
4665 
4666 	archive_string_free(&errlist);
4667 	return (ret);
4668 }
4669 #else
4670 /*
4671  * Restore extended attributes - stub implementation for unsupported systems
4672  */
4673 static int
4674 set_xattrs(struct archive_write_disk *a)
4675 {
4676 	static int warning_done = 0;
4677 
4678 	/* If there aren't any extended attributes, then it's okay not
4679 	 * to extract them, otherwise, issue a single warning. */
4680 	if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4681 		warning_done = 1;
4682 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4683 		    "Cannot restore extended attributes on this system");
4684 		return (ARCHIVE_WARN);
4685 	}
4686 	/* Warning was already emitted; suppress further warnings. */
4687 	return (ARCHIVE_OK);
4688 }
4689 #endif
4690 
4691 /*
4692  * Test if file on disk is older than entry.
4693  */
4694 static int
4695 older(struct stat *st, struct archive_entry *entry)
4696 {
4697 	/* First, test the seconds and return if we have a definite answer. */
4698 	/* Definitely older. */
4699 	if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry)))
4700 		return (1);
4701 	/* Definitely younger. */
4702 	if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4703 		return (0);
4704 	/* If this platform supports fractional seconds, try those. */
4705 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4706 	/* Definitely older. */
4707 	if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4708 		return (1);
4709 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4710 	/* Definitely older. */
4711 	if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4712 		return (1);
4713 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4714 	/* older. */
4715 	if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4716 		return (1);
4717 #elif HAVE_STRUCT_STAT_ST_UMTIME
4718 	/* older. */
4719 	if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4720 		return (1);
4721 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4722 	/* older. */
4723 	if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4724 		return (1);
4725 #else
4726 	/* This system doesn't have high-res timestamps. */
4727 #endif
4728 	/* Same age or newer, so not older. */
4729 	return (0);
4730 }
4731 
4732 #ifndef ARCHIVE_ACL_SUPPORT
4733 int
4734 archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4735     struct archive_acl *abstract_acl, __LA_MODE_T mode)
4736 {
4737 	(void)a; /* UNUSED */
4738 	(void)fd; /* UNUSED */
4739 	(void)name; /* UNUSED */
4740 	(void)abstract_acl; /* UNUSED */
4741 	(void)mode; /* UNUSED */
4742 	return (ARCHIVE_OK);
4743 }
4744 #endif
4745 
4746 /*
4747  * Close the file descriptor if one is open.
4748  */
4749 static void close_file_descriptor(struct archive_write_disk* a)
4750 {
4751 	if (a->fd >= 0) {
4752 		close(a->fd);
4753 		a->fd = -1;
4754 	}
4755 }
4756 
4757 
4758 #endif /* !_WIN32 || __CYGWIN__ */
4759 
4760