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