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